Parse string to date with moment.js - javascript

I want to parse the following string with moment.js 2014-02-27T10:00:00 and output
day month year (14 march 2014)
I have been reading the docs but without success
http://momentjs.com/docs/#/parsing/now/

I always seem to find myself landing here only to realize that the title and question are not quite aligned.
If you want a moment date from a string:
const myMomentObject = moment(str, 'YYYY-MM-DD')
From moment documentation:
Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.
If you instead want a javascript Date object from a string:
const myDate = moment(str, 'YYYY-MM-DD').toDate();

You need to use the .format() function.
MM - Month number
MMM - Month word
var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
FIDDLE

No need for moment.js to parse the input since its format is the standard one :
var date = new Date('2014-02-27T10:00:00');
var formatted = moment(date).format('D MMMM YYYY');
http://es5.github.io/#x15.9.1.15

moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.
function momentTest() {
var varDate = "2018-01-19 18:05:01.423";
var myDate = moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
var todayDate = moment().format("DD-MM-YYYY");
var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");
var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");
alert(todayDate);
if (myDate == todayDate) {
alert("date is today");
} else if (myDate == yesterdayDate) {
alert("date is yesterday");
} else if (myDate == tomorrowDate) {
alert("date is tomorrow");
} else {
alert("It's not today, tomorrow or yesterday!");
}
}

How to change any string date to object date (also with moment.js):
let startDate = "2019-01-16T20:00:00.000";
let endDate = "2019-02-11T20:00:00.000";
let sDate = new Date(startDate);
let eDate = new Date(endDate);
with moment.js:
startDate = moment(sDate);
endDate = moment(eDate);

Maybe try the Intl polyfill for IE8 or the olyfill service ?
or
https://github.com/andyearnshaw/Intl.js/

Related

Moment JS from yyyy-mm-ddthh:mm:ss to MM-DD-YY mm:ss [duplicate]

I want to parse the following string with moment.js 2014-02-27T10:00:00 and output
day month year (14 march 2014)
I have been reading the docs but without success
http://momentjs.com/docs/#/parsing/now/
I always seem to find myself landing here only to realize that the title and question are not quite aligned.
If you want a moment date from a string:
const myMomentObject = moment(str, 'YYYY-MM-DD')
From moment documentation:
Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.
If you instead want a javascript Date object from a string:
const myDate = moment(str, 'YYYY-MM-DD').toDate();
You need to use the .format() function.
MM - Month number
MMM - Month word
var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
FIDDLE
No need for moment.js to parse the input since its format is the standard one :
var date = new Date('2014-02-27T10:00:00');
var formatted = moment(date).format('D MMMM YYYY');
http://es5.github.io/#x15.9.1.15
moment was perfect for what I needed. NOTE it ignores the hours and minutes and just does it's thing if you let it. This was perfect for me as my API call brings back the date and time but I only care about the date.
function momentTest() {
var varDate = "2018-01-19 18:05:01.423";
var myDate = moment(varDate,"YYYY-MM-DD").format("DD-MM-YYYY");
var todayDate = moment().format("DD-MM-YYYY");
var yesterdayDate = moment().subtract(1, 'days').format("DD-MM-YYYY");
var tomorrowDate = moment().add(1, 'days').format("DD-MM-YYYY");
alert(todayDate);
if (myDate == todayDate) {
alert("date is today");
} else if (myDate == yesterdayDate) {
alert("date is yesterday");
} else if (myDate == tomorrowDate) {
alert("date is tomorrow");
} else {
alert("It's not today, tomorrow or yesterday!");
}
}
How to change any string date to object date (also with moment.js):
let startDate = "2019-01-16T20:00:00.000";
let endDate = "2019-02-11T20:00:00.000";
let sDate = new Date(startDate);
let eDate = new Date(endDate);
with moment.js:
startDate = moment(sDate);
endDate = moment(eDate);
Maybe try the Intl polyfill for IE8 or the olyfill service ?
or
https://github.com/andyearnshaw/Intl.js/

Why 1 day off when I try to convert date into toisostring in javascript?

I am trying to convert date object to ISOString() formate. But it return me 1 day off ( I mean it reduce 1 day ).
var fromDate = {
day:4,
month:5,
year:2012
}
var fromDateString = new Date(fromDate.year+'-'+fromDate.month+'-'+fromDate.day)
console.log(fromDateString.toISOString())
It is because of timezone, new Date() is in your current timezone, toISOString() is using standard timezone.
I have searched and I find best solution for every date object to convert in any format.
Comment if you agree?
var dateObj = {
day:2,
month:5,
year:2012
}
var date = new Date;
date.setFullYear(dateObj.year,dateObj.month-1,dateObj.day)
console.log(date)

Convert SQL datetime to string or Date object [duplicate]

How can I convert a string to a date time object in javascript by specifying a format string?
I am looking for something like:
var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat() function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
#Christoph Mentions using a regex to tackle the problem. Here's what I'm using:
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.
Edit: Maybe a bit more understandable in ES6 using destructuring:
let dateString = "2010-08-09 01:02:03"
, reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
, [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds);
But in all honesty these days I reach for something like Moment
No sophisticated date/time formatting routines exist in JavaScript.
You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.
For the input conversion, several suggestions have been made already. :)
Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).
Just for an updated answer here, there's a good js lib at http://www.datejs.com/
Datejs is an open source JavaScript Date library for parsing, formatting and processing.
var temp1 = "";
var temp2 = "";
var str1 = fd;
var str2 = td;
var dt1 = str1.substring(0,2);
var dt2 = str2.substring(0,2);
var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);
var yr1 = str1.substring(6,10);
var yr2 = str2.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;
var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);
var date1 = new Date(cfd);
var date2 = new Date(ctd);
if(date1 > date2) {
alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}
time = "2017-01-18T17:02:09.000+05:30"
t = new Date(time)
hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);
t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.
function ParseDate(dateString) {
//dd.mm.yyyy, or dd.mm.yy
var dateArr = dateString.split(".");
if (dateArr.length == 1) {
return null; //wrong format
}
//parse time after the year - separated by space
var spacePos = dateArr[2].indexOf(" ");
if(spacePos > 1) {
var timeString = dateArr[2].substr(spacePos + 1);
var timeArr = timeString.split(":");
dateArr[2] = dateArr[2].substr(0, spacePos);
if (timeArr.length == 2) {
//minutes only
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
} else {
//including seconds
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
}
} else {
//gotcha at months - January is at 0, not 1 as one would expect
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
}
}
Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.
Just to give my 5 cents.
My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.
I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/
and it worked, because you can say the order of the fields like this:
>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)
I hope that helps someone.
Moment.js will handle this:
var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;
You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.
Reference:
1. moment library: https://momentjs.com/
2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript
convertDate(date) {
var momentDate = moment(date).format('hh : mm A');
return momentDate;
}
and you can call this method like:
this.convertDate('2020-05-01T10:31:18.837Z');
I hope it helps. Enjoy coding.
To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822,
if you use yyyy-mm-dd parse may do a mistakes.
//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}

Date formatting and comparing dates

I want to check to see if a date is before today. If it is then I want to display the date but not the time, if it is today then I want to display the time and not the date. The date I am checking is in the dd-mm-yyy hh:mm format and so they do not compare.
Please see what I have below so far:
var created = '25-05-2012 02:15';
var now = new Date();
if (created < now) {
created_format = [ format the date to be 25-05-2012 ]
} else {
created_format = [ format the date to be 02:15 ]
}
I have tried using now.dateFormat() and now.format() after seeing these in other examples but I get "is not a function" error messages.
Start by getting the parts of your date string:
var created = '25-05-2012 02:15';
var bits = created.split(/[-\s:]/);
var now = new Date();
// Test if it's today
if (bits[0] == now.getDate() &&
bits[1] == (now.getMonth() + 1) &&
bits[2] == now.getFullYear() ) {
// date is today, show time
} else {
// date isn't today, show date
}
Of course there are other ways, but I think the above is the easiest. e.g.
var otherDate = new Date(bits[2], bits[1] - 1, bits[0]);
now.setHours(0,0,0,0);
if (otherDate < now) {
// otherDate is before today
} else {
// otherDate is not before today
}
Similarly, once you've converted the string to a date you can use getFullYear, getMonth, getDate to compare with each other, but that's essentially the same as the first approach.
You can use getTime method and get timestamp. Then you can compare it with current date timestamp.

How can I convert string to datetime with format specification in JavaScript?

How can I convert a string to a date time object in javascript by specifying a format string?
I am looking for something like:
var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat() function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
#Christoph Mentions using a regex to tackle the problem. Here's what I'm using:
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.
Edit: Maybe a bit more understandable in ES6 using destructuring:
let dateString = "2010-08-09 01:02:03"
, reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
, [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds);
But in all honesty these days I reach for something like Moment
No sophisticated date/time formatting routines exist in JavaScript.
You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.
For the input conversion, several suggestions have been made already. :)
Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).
Just for an updated answer here, there's a good js lib at http://www.datejs.com/
Datejs is an open source JavaScript Date library for parsing, formatting and processing.
var temp1 = "";
var temp2 = "";
var str1 = fd;
var str2 = td;
var dt1 = str1.substring(0,2);
var dt2 = str2.substring(0,2);
var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);
var yr1 = str1.substring(6,10);
var yr2 = str2.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;
var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);
var date1 = new Date(cfd);
var date2 = new Date(ctd);
if(date1 > date2) {
alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}
time = "2017-01-18T17:02:09.000+05:30"
t = new Date(time)
hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);
t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.
function ParseDate(dateString) {
//dd.mm.yyyy, or dd.mm.yy
var dateArr = dateString.split(".");
if (dateArr.length == 1) {
return null; //wrong format
}
//parse time after the year - separated by space
var spacePos = dateArr[2].indexOf(" ");
if(spacePos > 1) {
var timeString = dateArr[2].substr(spacePos + 1);
var timeArr = timeString.split(":");
dateArr[2] = dateArr[2].substr(0, spacePos);
if (timeArr.length == 2) {
//minutes only
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
} else {
//including seconds
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
}
} else {
//gotcha at months - January is at 0, not 1 as one would expect
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
}
}
Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.
Just to give my 5 cents.
My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.
I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/
and it worked, because you can say the order of the fields like this:
>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)
I hope that helps someone.
Moment.js will handle this:
var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;
You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.
Reference:
1. moment library: https://momentjs.com/
2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript
convertDate(date) {
var momentDate = moment(date).format('hh : mm A');
return momentDate;
}
and you can call this method like:
this.convertDate('2020-05-01T10:31:18.837Z');
I hope it helps. Enjoy coding.
To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822,
if you use yyyy-mm-dd parse may do a mistakes.
//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}

Categories

Resources