Reputation: 125
I have a variable that contains JSON data with thousands of rows. Some of the variables are dates in the following format Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)
. I need to convert all of these variables into a more usable date format such as `mm/dd/yyyy'.
Any suggestions on how to accomplish this?
{
"request": [
{ "startdate":"Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)" ,
"status":"in progress" }, ...
]}
Thanks in advance!
Upvotes: 0
Views: 1499
Reputation: 147523
Always best to convert a string to a date object is to manually parse it unless you have a very controlled environment. The following should do the job:
// Use date string to create a UTC time to pass to Date constructor
// Expected format is day mon year hh:mm:ss GMToffset (timezone name)
// e.g. Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)
function parseDate(s) {
var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
var s = s.split(/[ :]/g);
var offset = s[7];
// Deal with offset
var sign = offset.indexOf('-') >= 0? -1 : 1;
var len = offset.length;
var offMins = sign * offset.substring(len-4, len-2) * 60 + sign * offset.substring(len-2, len);
var mins = s[4] - offMins;
return new Date(Date.UTC(s[3], months[s[1].toLowerCase()], s[2], s[4], mins, s[6]));
}
var s = 'Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)';
alert(parseDate(s)); //Fri 27 Jun 2008 17:00:00 GMT+1000
You can then format the date however you want:
function formatDateUS(d) {
function z(n){return (n<10? '0':'') + n}
return z(d.getMonth()+1) + '/' + z(d.getDate()) + '/' + d.getFullYear();
}
formatDateUS(parseDate(s)); // 06/27/2008
Upvotes: 1
Reputation: 882
Try the following:
var json = {
"request": [
{ "startdate":"Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)" ,
"status":"in progress" }
]};
var date = new Date(json.request[0].startdate);
var formatDate = function(date) {
var mm = date.getMonth()+1;
mm = mm > 10 ? mm : "0"+mm;
var dd = date.getDate();
dd = dd > 10 ? dd : "0"+dd;
var yy = date.getFullYear();
return mm+"/"+dd+"/"+yy;
}
var formattedDate = formatDate(date);
Upvotes: 2
Reputation: 679
You can pass the date string as an argument when instantiating the Date class. Javascript doesn't have a good date formatter, but you can easily roll your own. For instance:
function parseDate(date) {
var d = new Date(date);
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();
if(month < 10) month = '0' + month;
if(day < 10) day = '0' + day;
return month + '/' + day + '/' + year;
}
parseDate('Fri Jun 27 2008 00:00:00 GMT-0700 (US Mountain Standard Time)');
// returns "06/27/2008"
Upvotes: 3