Remove Seconds/ Milliseconds from Date convert to ISO String

前端 未结 9 1802
滥情空心
滥情空心 2020-12-15 15:41

I have a date object that I want to

  1. remove the miliseconds/or set to 0
  2. remove the seconds/or set to 0
  3. Convert to ISO string

F

相关标签:
9条回答
  • 2020-12-15 16:03

    There is no need for a library, simply set the seconds and milliseconds to zero and use the built–in toISOString method:

    var d = new Date();
    d.setSeconds(0,0);
    document.write(d.toISOString());

    Note: toISOString is not supported by IE 8 and lower, there is a pollyfil on MDN.

    0 讨论(0)
  • 2020-12-15 16:06

    This version works for me (without using an external library):

    var now = new Date();
    now.setSeconds(0, 0);
    var stamp = now.toISOString().replace(/T/, " ").replace(/:00.000Z/, "");
    

    produces strings like

    2020-07-25 17:45
    

    If you want local time instead, use this variant:

    var now = new Date();
    now.setSeconds(0, 0);
    var isoNow = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
    var stamp = isoNow.replace(/T/, " ").replace(/:00.000Z/, "");
    
    0 讨论(0)
  • 2020-12-15 16:12

    Pure javascript solutions to trim off seconds and milliseconds (that is remove, not just set to 0). JSPerf says the second funcion is faster.

    function getISOStringWithoutSecsAndMillisecs1(date) {
      const dateAndTime = date.toISOString().split('T')
      const time = dateAndTime[1].split(':')
      
      return dateAndTime[0]+'T'+time[0]+':'+time[1]
    }
    
    console.log(getISOStringWithoutSecsAndMillisecs1(new Date()))

     
    function getISOStringWithoutSecsAndMillisecs2(date) {
      const dStr = date.toISOString()
      
      return dStr.substring(0, dStr.indexOf(':', dStr.indexOf(':')+1))
    }
    
    console.log(getISOStringWithoutSecsAndMillisecs2(new Date()))

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