Remove Seconds/ Milliseconds from Date convert to ISO String

六月ゝ 毕业季﹏ 提交于 2019-11-30 10:53:17

While this is easily solvable with plain javascript (see RobG's answer), I wanted to show you the momentjs solution since you tagged your questions as momentjs:

moment().seconds(0).milliseconds(0).toISOString();

This gives you the current datetime, without seconds or milliseconds.

Working example: http://jsbin.com/bemalapuyi/edit?html,js,output

From the docs: http://momentjs.com/docs/#/get-set/

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.

A bit late here but now you can:

var date = new Date();

this obj has:

date.setMilliseconds(0);

and

date.setSeconds(0);

then call toISOString() as you do and you will be fine.

No moment or others deps.

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()))

You can use the startOf() method within moment.js to achieve what you want.

Here's an example:

var date = new Date();

var stringDateFull = moment(date).toISOString();
var stringDateMinuteStart = moment(date).startOf("minute").toISOString();

$("#fullDate").text(stringDateFull);
$("#startOfMinute").text(stringDateMinuteStart);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.js"></script>
<p>Full date: <span id="fullDate"></span></p>
<p>Date with cleared out seconds: <span id="startOfMinute"></span></p>
let date = new Date();
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());

I hope this works!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!