tags:

views:

265

answers:

3

I'm using calendar from Yahoo UI as follows:

calDate = (calDate.getMonth() + 1) + '/' + calDate.getDate() + '/' + calDate.getFullYear();

This displays a MMDDYYYY format.

I want to change this format to YYYY-MM-DD so that I can insert it into a MySQL database. I changed the code to:

calDate = calDate.getFullYear() + '-' + (calDate.getMonth() + 1) + '-' + calDate.getDate();

It worked but the problem is now that when I want to change the selected date the calender doesn't display the date and instead shows NAN.

+1  A: 

You should change the format of the date just before it is inserted on the server side, let the client side have the format that it wants, and change the date around later.

Seventoes
+2  A: 

It's typically best to pass the date to your back end as a unix timestamp and convert it in the database itself. In the code where you construct your POST data for the server, you'd pass something like this:

var t = calDate.getTime()/1000;

Note the divide by 1000. This is required because javascript timestamps are in milliseconds, while MySQL requires seconds.

In your SQL statement, you'll pass the timestamp as is, and use the FROM_UNIXTIME function to convert it to your required format:

INSERT INTO ... VALUES ( FROM_UNIXTIME($t), ...)

Naturally there will be some code in between that converts t from javascript into $t in your back end script, and then passes that on to the SQL.

Now, if you really need to format dates on the front end, you can make use of the handy YAHOO.util.Date utility. Just do something like this:

alert(YAHOO.util.Date.format(calDate, {format: "%Y-%m-%d" }));

Much easier than calling getFullYear, getMonth, and getDate

bluesmoon
+2  A: 

bluesmoon has also written two excellent articles on YUIBlog on the subject of date formatting:

  1. http://yuiblog.com/blog/2009/02/11/date-formatting-pt1-2/
  2. http://yuiblog.com/blog/2009/02/25/date-formatting-pt2/

-Eric

Eric Miraglia