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!
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"
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);
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
Related
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 2 years ago.
I must to get properly date value from my long date in string.
I have this date:
Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time)
how to parse this date to: 2020-08-30?
and i have another use case:
Tue Aug 25 2020 11:58:04 GMT+0200 (Central European Summer Time)
how to parse this date to: 11:58?
thanks for any help :)
//////////////////////////////////////////////////////////////
If you're sure that your strings are always in that format, you could just split on spaces:
date = "Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time)";
[day_of_week, month, day, year, time, ...tz] = date.split(" ");
tz = tz.join(" "); // combine timezone back into one string
You could process this further, but you might want to look more into Date: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
This would work:
const formatDate = (date) => {
const d = new Date(date);
let month = '' + (d.getMonth() + 1);
let day = '' + d.getDate();
const year = d.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return [year, month, day].join('-');
}
// Would print 2020-08-30
console.log(formatDate('Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time)'))
You could use Date node build in lib or moment. If you’re planning to do a lot of date manipulation I would suggest use moment npm package
For getting the date version
moment(your string).format(“YYYY-MM-DD”)
For getting the time
moment(your string).format(“HH:mm”)
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
you can use this or if you want to use 3rd party lib moment.js (https://momentjs.com/) is the best and easy to implement
Say that I have DateTime in this format Fri Feb 02 2018 00:00:00 GMT+0530 (IST)
And from the time picker plugin getting the time 1:10am or 2:30pm in this format.
I am not sure how to calculate and combine/add them both to produce this result:
Fri Feb 02 2018 01:10:00 GMT+0530 (IST) or Fri Feb 02 2018 14:30:00 GMT+0530 (IST)
I wish if there was something to do as simple as this:
new Date(dateString).setHours(1:10am)
Seems like you need to parse it on your own:
function parseDaytime(time) {
let [hours, minutes] = time.substr(0, time.length -2).split(":").map(Number);
if (time.includes("pm") && hours !== 12) hours += 12;
return 1000/*ms*/ * 60/*s*/ * (hours * 60 + minutes);
}
To add it to a date:
new Date(
+new Date("Fri Feb 02 2018 00:00:00 GMT+0530")
+parseDaytime("1:20pm")
);
Here is a simple function to do what your after.
It basically splits the time using a regex, and then calls setHours & setMins, adding 12 hours if pm is selected.
The example below takes the current datetime, and sets 1:10am & 2:40pm..
function setHours(dt, h) {
var s = /(\d+):(\d+)(.+)/.exec(h);
dt.setHours(s[3] === "pm" ?
12 + parseInt(s[1], 10) :
parseInt(s[1], 10));
dt.setMinutes(parseInt(s[2],10));
}
var d = new Date();
console.log(d);
setHours(d, "1:10am");
console.log(d);
setHours(d, "2:40pm");
console.log(d);
You can parse the time string into hours & minutes, adjust the hours according to am/pm & set it to the date object then:
var dateString = 'Fri Feb 02 2018 00:00:00 GMT+0530 (IST)';
var hoursString = '2:30pm';
var parts = hoursString.replace(/am|pm/, '').split(':')
var hours = parseInt(parts[0]) + (hoursString.indexOf('pm') !== -1 ? 12 : 0);
var minutes = parts[1];
var date = new Date(dateString);
date.setUTCHours(hours, minutes);
console.log(date); // in your local time
console.log(date.toUTCString()); // in UTC (i.e. without timezone offset)
(Note setHours / setUTCHours mutates date object but returns unix timestamp of the updated datetime.)
In Javascript, I have date string as shown below:
var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
I need to convert it to "YYYYMMDD" format. For example the above date should be : "20150325"
A good function for doing that which I found and used it always.
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};
var date = new Date();
date.yyyymmdd();
Here's a dirty hack to get you started. There are numerous ways of achieving the format you want. I went for string manipulation (which isn't the best performance).
var someDate = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
var dateFormated = someDate.toISOString().substr(0,10).replace(/-/g,"");
alert(dateFormated);
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + month + day;
}
And then just call the function :
alert(getFormattedDate(new Date());
The Date object is able to parse dates as string d = new Date( dateStr ); provided that they are properly formatted like the example in your question.
The Date object also offers methods to extract from the instance the year, month and day.
It's well documented and there are plenty of examples if you just Google for it.
What is worth mentioning is that the Date object doesn't handle timezone and the internal date-time is always converted into the client's timezone.
For example here's what I get if I try to parse your date in my browser (I'm in GMT+01):
dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
d = new Date( dateStr );
---> Wed Mar 25 2015 01:00:00 GMT+0100 (CET) = $2
If you need to handle timezone properly the easiest way is to use a library like MomentJS
I need to convert this date format : Fri Jul 29 2016 00:00:00 GMT+0100 (Maroc (heure d’été)) (I don't what do we call it by the way ) to iso format (yyyy-mm-dd 00:00:00.000 ) using javascript
Thanks in advance
Here is sample snippet for your query. I hope it helps for your query.
function formatDate(date) {
var d = new Date("Fri Jul 29 2016 00:00:00 GMT+0100"),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
Using moment.js:
moment(new Date("Fri Jul 29 2016 00:00:00 GMT+0100")).format("Y-MM-DD HH:mm:ss.SSS")
I'm getting a strange result:
var date = new Date();
var year = date.getMonth() < 11 ? date.getFullYear() : date.getFullYear() + 1;
var month = date.getMonth() < 11 ? date.getMonth() + 1 : 0;
console.log(new Date(Date.UTC(year, month)));
var utcYear = date.getUTCMonth() < 11 ? date.getUTCFullYear() : date.getUTCFullYear() + 1;
var utcMonth = date.getUTCMonth() < 11 ? date.getUTCMonth() + 1 : 0;
console.log(new Date(utcYear, utcMonth));
With the particular date I'm using (any date will do), Date.UTC gives me:
Sun May 31 2015 19:00:00 GMT-0500 (Central Daylight Time)
The getUTC... aproach gives me:
Mon Jun 01 2015 00:00:00 GMT-0500 (Central Daylight Time)
Am I mis-using Date.UTC or am I missing something?
Thanks
You are creating a Date using UTC time, but then you are displaying it in local time, that's why it's a few hours behind. Use Date.prototype.toUTCString() to see the UTC time
var date = new Date();
var year = date.getMonth() < 11 ? date.getFullYear() : date.getFullYear() + 1;
var month = date.getMonth() < 11 ? date.getMonth() + 1 : 0;
// It's a UTC date, display it as UTC, not local time
console.log(new Date(Date.UTC(year, month)).toUTCString());
var utcYear = date.getUTCMonth() < 11 ? date.getUTCFullYear() : date.getUTCFullYear() + 1;
var utcMonth = date.getUTCMonth() < 11 ? date.getUTCMonth() + 1 : 0;
// Created using local time, you can just use the normal toString()
console.log(new Date(utcYear, utcMonth));
This code is to get the first day of the next month (something that reoccurs monthly and can't start until next month).
Then you're looking for
var today = new Date(); // now
var utcYear = today.getUTCMonth() < 11 ? today.getUTCFullYear() : today.getUTCFullYear() + 1;
var utcMonth = today.getUTCMonth() < 11 ? today.getUTCMonth() + 1 : 0;
var date = new Date(Date.UTC(utcYear, utcMonth)); // next UTC month
console.log(date.toString()); // Mon Jun 01 2015 02:00:00 GMT+0200
// or, in your timezone: Sun May 31 2015 19:00:00 GMT-0500 (same moment)
console.log(date.toUTCString()); // Mon, 01 Jun 2015 00:00:00 GMT
Btw, the Date methods does take too large values into accout (and carry-over them automatically), so you just would need to do
var today = new Date(); // now
var date = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth()+1)); // next UTC month