format date using javascript

后端 未结 3 1270
小鲜肉
小鲜肉 2021-01-26 15:44

have problem for format date in JavaScript, this is my function code

   //originalDate = \'2016-03-02 09:12:14.989522\';
   var d = new Date(originalDate),
             


        
相关标签:
3条回答
  • 2021-01-26 16:26

    Simple solution: Replace the space in your date string with a "T".

    (However, to be completely technically correct, you should also include a time zone indicator at the end, either an additional "Z" to indicate UTC, i.e. Coordinated Universal Time, or "+hh:mm" or "-hh:mm" to indicate a time zone offset.)

    The MDN site for Date.parse() writes:

    Because of the variances in parsing of date strings, ...results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

    and

    The date time string may be in ISO 8601 format.

    The ISP 8601 specs referred to above writes:

    The formats are as follows. Exactly the components shown here must be present, with exactly this punctuation. Note that the "T" appears literally in the string, to indicate the beginning of the time element, as specified in ISO 8601.

    and

    Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)

    Here is your code re-written replacing the space in date with a "T". If that doesn't work in your browser, add a "Z" or time zone offset at the end of date.

    var date ='2016-03-02T09:12:14.989522';
    var d = new Date(date),
      month = d.getMonth() + 1,
      day = d.getDate(),
      year = d.getFullYear(),
      hour = d.getHours(),
      min = d.getMinutes();
    document.write([day, month, year].join('-') + ' ' + [hour, min].join(':'));

    0 讨论(0)
  • 2021-01-26 16:29

    First parse your original date then use it in your code.

    var MilliSecond=Date.parse(originalDate);
    var d=new Date(MilliSecond),
    month=d.getMonth()+1,
    day=d.getDay(), .......
    
    0 讨论(0)
  • 2021-01-26 16:32

    Is the date parameter in your code a Date object? That won't work. There is no such constructor in Javascript. You could use date.now() though.

    Check here for the valid constructors for Date https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date

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