views:

54

answers:

4

Hi, I have this string: 2010-09-21T15:48:12.754+02:00

I would transform it in this format: Tue Sep 21 15:48:12 CEST 2010

How can I do it with javascript or jQuery?

Thanks a lot. MP.

+1  A: 

Try this:

var myDate = new Date("2010-09-21T15:48:12.754+02:00")
alert(myDate);

EDIT

If you want, you can write your own date format, for example:

var date = new Date("2010-09-21T15:48:12.754+02:00");
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; 
var myDate = '';
myDate += days[date.getDay()] + " " + months[date.getMonth()] + " " + date.getDate() + " ";
myDate += date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + " ";
myDate += "0" + date.getTimezoneOffset() / 60 + ":00 " + date.getFullYear();
alert(myDate);

See in jsfiddle.


EDIT

Another example:

// crazy date
var date = new Date("2010-09-22");
var days = ['Weekend!', 'Workday', 'Workday', 'Workday', 'Workday', 'Workday', 'Weekend!'];
var months = ['Winter', 'Winter', 'Spring', 'Spring', 'Spring', 'Summer', 'Summer', 'Summer', 'Autumn', 'Autumn', 'Autumn', 'Winter'];
var myDate = "We are in " + months[date.getMonth()] + " and today is a " +  days[date.getDay()];
alert(myDate);
Topera
I have tried your code but it doesn't work. The output is:
michele
undefined undefined NaN NaN:NaN:NaN 0NaN:00 NaN
michele
It works on firefox 3.6. Which browser are you using?
Topera
A: 

As per Topera, create a date object, then use the objects methods to create the string formatted as you like.

Here's a reference: http://www.w3schools.com/jsref/jsref_obj_date.asp

Nik
A: 

Try this:

var d = new Date("2010-09-21T15:48:12.754+02:00");
var date = d.toDateString().split(/\s/);
var time = d.getHours() +':'+ d.getMinutes() +':'+ d.getSeconds();
date.splice(3, 3, time, 'CEST', d.getFullYear());
date.join(' '); // Tue Sep 21 15:48:12 CEST 2010 
erickb
I have tried it but I have returned:
michele
We are in undefined and today is a undefined
michele
you can assign date.join(' ') to the undefined variable: d = date.join(' ')
erickb
A: 

Solved.

var datasplit=obj.requests[i].start.split("T");

                    datasplit[1]=datasplit[1].slice(0,7);

                    var d = new Date(datasplit[0]+" "+datasplit[1]);
                    var date = d.toDateString().split(/\s/);
                    var time = d.getHours() +':'+ d.getMinutes() +':'+ d.getSeconds();
                    date.splice(3, 3, time, 'CEST', d.getFullYear());
                    date.join(' '); // Tue Sep 21 15:48:12 CEST 2010
                    //alert(date);
                    var data=date.toString();
                    data=data.replace(/,/g," ");

Thank you.

michele