Reputation: 265
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?
Upvotes: 1
Views: 7402
Reputation: 55
Step 1 you are getting date from input type date like below
like 2021-08-18 as string
then
var formatted date = date.split('-')[2]+"/"+date.split('-')1+"/"+date.split('-')[0])
result will be 18/08/2021
Upvotes: -1
Reputation: 7187
I know this is a year old and has an accepted answer. Just in case someone comes around looking...
You can append the timezone information to the formatted string and create a date object to get what you want.
var x = "08/07/2010 11:22:00 AM".split('/');
var d = new Date(x[1] + '/' + x[0] + '/' + x[2] + " GMT");
Just to make sure I understand what you wanted, I ran the accpeted answer along with this, both return the same result.
Upvotes: 1
Reputation: 265
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
Upvotes: 0
Reputation: 24472
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 :)
Upvotes: 1
Reputation: 6581
function switchFormat(dateString) {
var a = dateString.split('/'),
b;
b = a[0];
a[0] = a[1];
a[1] = b;
return a.join('/');
}
Edited
Upvotes: 0
Reputation: 85862
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];
Upvotes: 1