Remove Seconds/ Milliseconds from Date convert to ISO String

JavascriptDateMomentjsIsodate

Javascript Problem Overview


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

For example:

var date = new Date();
//Wed Mar 02 2016 16:54:13 GMT-0500 (EST)

var stringDate = moment(date).toISOString();
//2016-03-02T21:54:13.537Z

But what I really want in the end is

stringDate = '2016-03-02T21:54:00.000Z'

Javascript Solutions


Solution 1 - Javascript

While this is easily solvable with plain JavaScript (see RobG's answer), I wanted to show you the Moment.js 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/

Solution 2 - Javascript

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.

Solution 3 - Javascript

A non-library regex to do this:

new Date().toISOString().replace(/.\d+Z$/g, "Z");

This would simply trim down the unnecessary part. Rounding isn't expected with this.

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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/, "");

Solution 7 - Javascript

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>

Solution 8 - Javascript

We can do it using plain JS aswell but working with libraries will help you if you are working with more functionalities/checks.

You can use the moment npm module and remove the milliseconds using the split Fn.

const moment = require('moment')

const currentDate = `${moment().toISOString().split('.')[0]}Z`;

console.log(currentDate) 

Refer working example here: https://repl.it/repls/UnfinishedNormalBlock

Solution 9 - Javascript

let date = new Date();
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());

I hope this works!!

Solution 10 - Javascript

Luxon could be your friend

You could set the milliseconds to 0 and then suppress the milliseconds using suppressMilliseconds with Luxon.

DateTime.now().toUTC().set({ millisecond: 0 }).toISO({
  suppressMilliseconds: true,
  includeOffset: true,
  format: 'extended',
}),

leads to e.g.

> 2022-05-06T14:17:26Z

Solution 11 - Javascript

To remove the seconds and milliseconds values this works for me:

const stringDate = moment()

// Remove milliseconds

console.log(moment.utc(stringDate).format('YYYY-MM-DDTHH:mm:ss[Z]'))

// Remove seconds and milliseconds

console.log(moment.utc(stringDate).format('YYYY-MM-DDTHH:mm[Z]'))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontester123View Question on Stackoverflow
Solution 1 - JavascriptjszobodyView Answer on Stackoverflow
Solution 2 - JavascriptRobGView Answer on Stackoverflow
Solution 3 - JavascriptAbhilashView Answer on Stackoverflow
Solution 4 - JavascriptJimmy KaneView Answer on Stackoverflow
Solution 5 - JavascriptipsView Answer on Stackoverflow
Solution 6 - Javascriptmar10View Answer on Stackoverflow
Solution 7 - JavascriptSarhanisView Answer on Stackoverflow
Solution 8 - JavascriptaakarshView Answer on Stackoverflow
Solution 9 - JavascriptVishal VariyaniView Answer on Stackoverflow
Solution 10 - JavascriptH6.View Answer on Stackoverflow
Solution 11 - JavascriptDwight RodriquesView Answer on Stackoverflow