How to parse date in JS? [duplicate] - javascript

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

Related

convert date format to 'YYYYMMDD'

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

Convert time format to iso format

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")

How to change date format in JS

I found a solution to transform a date like:
Thu Sep 04 2014 00:00:00 GMT+0200 (Romance Daylight Time)
to a format french 04/09/2014
How can i achieve this?
You can do that by using the Date object and its functions:
function zerofy(number){
if(number < 10)
number = "0" + number;
return number;
}
var date = new Date("Thu Sep 04 2014 00:00:00 GMT+0200 (Romance Daylight Time)");
var day = zerofy(date.getDate());
var month = zerofy(date.getMonth());
var year = date.getFullYear();
var result = day + "/" + month + "/" + year
console.log(result);
Working Demo
I would recommend going over this document from MDN for these kind of problems.
Perhaps a basic one-liner would help?
function formatDate(date){
return [('0'+date.getDate()).slice(-2),('0'+date.getMonth()).slice(-2),date.getFullYear()].join('/');
}

Javascript date formatting Fri Jun 21 00:00:00 UTC+0100 2013 to iso 8601 (2013-06-21)

Please advise:
Is there a way without regex or string replaces and so forth to convert a simple date such as:
Fri Jun 21 00:00:00 UTC+0100 2013
To a ISO8601 formatted date yy-mm-dd?
PS: 8601 date only, not date time.
Use moment.js http://momentjs.com/
moment(new Date(), "YYYY-MM-DD HH:mm Z");
or:
var date = moment("Fri Jun 21 00:00:00 UTC+0100 2013");
moment("Fri Jun 21 00:00:00 UTC+0100 2013", "YYYY-MM-DD HH:mm Z");
You can parse it and format it very easily whatever way you want http://momentjs.com/docs/ it is compatible with ISO-8601 dates for parsing as well.
Yes !
the date function in javascript.
var d = new Date("Fri Jun 21 00:00:00 UTC+0100 2013")
alert( d.getFullYear() + '-' + d.getUTCMonth() + '-' + d.getUTCDay())
2 lines of code :)
more info here : http://www.w3schools.com/jsref/jsref_obj_date.asp
Without regexes or string replaces? Yes, assuming that the format is fixed you could use .slice() and/or .substr() to extract the particular bits you need and rearrange them (unless such methods fall into your category of "and so forth"):
var input = "Fri Jun 21 00:00:00 UTC+0100 2013";
var year = input.slice(-4),
month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(input.substr(4,3))+1,
day = input.substr(8,2);
var output = year + '-' + (month<10?'0':'') + month + '-' + day;
Or you could go ahead and get silly with a regex replace:
var output = input.replace(/^[^\s]+\s([^\s]+)\s(\d+)\s.*(\d{4})$/,function(m,p1,p2,p3) {
var month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(p1)+1;
return p3 + '-' + (month<10?'0':'') + month + '-' + (p2.length===1?'0':'') + p2;
});
Of course you'd probably want to wrap such code in a reformatDate() method.
(For a "simple" reformatting of a date string, the Date object and its methods aren't particularly helpful unless the starting format is one recognised by Date.parse().)
Why dont you try to use the get functions, like getDate(), getMonth(), etc. For example:
var today = new Date();
var d1 = new Date();
alert(d1);
var date = d1.getDate();
var month = d1.getMonth() + 1;
var year = d1.getFullYear();
Then configure the string the way you want it to appear...!

Convert Date Format in JSON variable

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

Categories