操作后如何保持原始日期格式?

时间:2018-05-24 09:21:44

标签: javascript datetime

我的参考日期如下:

  

2018-05-23T17:02:59 + 02:00

我需要从此参考日期减去1(毫秒)秒,然后以完全相同的格式返回它,如下所示:

  

2018-05-23T17:02:58 + 02:00

我成功地去了同一天的前一秒:

var refTime = '2018-05-23T17:02:59+02:00';
var d = new Date(refTime);
var nd = d.setMilliseconds(-1);

但我无法找到如何以与nd完全相同的格式输出refTime

我该怎么办?

3 个答案:

答案 0 :(得分:0)

更新:只需将1减去日期。

// 1ms difference
d.getMilliseconds() // 999  
newdate2.getMilliseconds() // 998

var refTime = '2018-05-23T17:02:59+02:00';
var d = new Date(refTime);
var nd = d.setMilliseconds(-1);

// new date 
var newdate = new Date(d - 1);
console.log(newdate);

答案 1 :(得分:0)

//Get second and set subtracting a second
var refTime = '2018-05-23T17:02:59+02:00';
var d = new Date(refTime);
var nd = d.setSeconds(d.getSeconds() - 1);
console.log(new Date(nd))

答案 2 :(得分:0)

//Using moment js
var refTime = '2018-05-23T17:02:59+02:00';
var d = new moment(refTime);
var nd = d.subtract(1, 'seconds')
console.log(new moment(nd))
<script src="https://momentjs.com/downloads/moment.min.js"></script>