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

前端 未结 15 1021
终归单人心
终归单人心 2020-11-22 02:35

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         


        
相关标签:
15条回答
  • 2020-11-22 03:00

    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

    0 讨论(0)
  • 2020-11-22 03:04

    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.

    0 讨论(0)
  • 2020-11-22 03:07

    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.

    0 讨论(0)
  • 2020-11-22 03:08

    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.

    0 讨论(0)
  • 2020-11-22 03:09

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

    0 讨论(0)
  • 2020-11-22 03:09

    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.

    0 讨论(0)
提交回复
热议问题