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 = convert
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
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.
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.
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.
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. :)
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.