tags:

views:

68

answers:

4

The timestamp I get from a server's SOAP response is formatted in European Notation and in GMT time (ex: 08/07/2010 11:22:00 AM). I want to convert it to local time and change the formatting to (MM/DD/2010 HH:MM:SS AM/PM).

I know about the JavaScript Date object but can't figure out the logic of how to do the conversion. Can anyone help me?

A: 
function switchFormat(dateString) {
    var a = dateString.split('/'),
        b;
    b = a[0];
    a[0] = a[1];
    a[1] = b;
    return a.join('/');
}

Edited

Try it here

lawnsea
+1  A: 

Do you really need date objects for this? If all you're doing is switching the first two parts of a string of that exact format,

var pieces = str.split('/');
str = pieces[1] + '/' + pieces[0] + '/' + pieces[2];
Matchu
This worked great for switching the formatting, but I also need to adjust the time from GMT to local.
Mark Cheek
A: 

Parse dates using:

Date.parse("08/07/2010 11:22:00 AM");

To convert the GMT date to local date (one on the browser or js useragent) use the following function:

     function getLocalTime(gmt)  {
       var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
       var localNow = new Date().getTimezoneOffset(); // get the timezone 
                                                      // offset in minutes            
       var localTime = min - localNow; // get the local time
       return new Date(localTime * 1000 * 60); // convert it into a date
    }

    var dt = new Date(Date.parse("08/07/2010 11:22:00 AM"));
    var localDate = getLocalTime(dt);

Next is date formatting, which is quite simple. Call the following functions on your newly obtained (local) date:

localDate.getXXX(); // where XXX is Hour, Minutes, etc.

Note: Tested in FF. Tweak as required in other browsers :)

naikus
I'm GMT -5 and this changes my time by 5 minutes, not 5 hours
Mark Cheek
My mistake: My minute conversion formula was stupidly wrong. It works now as desired.
naikus
A: 
var serverTimestamp = storArray[a][0];
var pieces = serverTimestamp.split('/'); 
storArray[a][0] = pieces[1] + '/' + pieces[0] + '/' + pieces[2];
var gmt = new Date(storArray[a][0]);
var localTime = gmt.getTime() - (gmt.getTimezoneOffset() * 60000); // convert gmt date to minutes
var localDate = new Date(localTime); // convert it into a date 
Mark Cheek
This is what I ended up doing. the storArray variable is the place in the array where the timestamp is
Mark Cheek