69

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'
tester123
  • 1,033
  • 2
  • 12
  • 17

13 Answers13

62

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • 6
    But this still shows the millis. Is there not a way to remove the millis without a library and without splice or some type of regex? I am surprised we can not just format the date object the way we want like in PHP. – wuno Feb 02 '17 at 02:32
  • @wuno—wouldn't that be great? Unfortunately ECMAScript Date objects have no formatting support at all, absolutely none. There is the [*Intl.DateTimeFormat*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat) supported by [*Date.prototype.toLocaleString*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) for some browsers, but it's not definitive in specifying the result. A good parsing and formatting library is [*fecha.js*](https://github.com/taylorhakes/fecha). – RobG Feb 02 '17 at 03:11
  • Yes it would be lol. I went ahead and used toISOString() then used the substring(0,19) method. Do you think that is safe? Also if the date suggested format is this, 2007-07-25T11:46:24 is it is safe to assume that it does not need to be UTC? Because leaving that out will just leave it up to the server location to set the time and date based on the server's timezone. Am I correct? Thanks for your help! – wuno Feb 02 '17 at 03:15
  • 9
    @wuno—if you omit the timezone it will be treated as "local". If you want it as UTC, always include the "Z". As for milliseconds, they're required by ECMA-262 so should always be there. Use a regular expression if in doubt: `date.toISOString().replace(/\.\d+Z/,'Z')` should remove any decimal seconds part. – RobG Feb 02 '17 at 04:17
  • this one is perfect for me – RadekR Feb 24 '22 at 16:05
  • Thanks, @RobG! `.replace(/\.\d+Z/,'')` did the trick for me to remove milliseconds and timezone altogether. – LucianoBAF Jun 21 '23 at 20:29
59

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/

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
jszobody
  • 28,495
  • 6
  • 61
  • 72
  • there is no need to use moment for such simple date things :) moment is officially legacy: https://momentjs.com/docs/ – spierala Jan 06 '21 at 15:21
  • 4
    @spierala Yes I know, but this was 2016 – jszobody Jan 07 '21 at 16:03
  • It STILL shows the milliseconds (like .000 now). So it's not removed from the string! For example: `moment().milliseconds(0).toISOString(true)` Will result into: 2023-03-31T15:59:55.000+02:00 – Melroy van den Berg Mar 31 '23 at 15:00
  • Because I have a +02:00 hours different in UTC. I use: `.replace(/\.\d+\+/,'+')` to get right of the milliseconds.. It's not pretty. – Melroy van den Berg Mar 31 '23 at 15:03
  • @MelroyvandenBerg The goal was to strip the millisecond VALUE (set to 0), and this accomplished that goal. The ISO string is still going to have `000` as part of the string, that's on purpose. – jszobody Apr 01 '23 at 23:26
  • In my specific case I wanted to remove the milliseconds completely from the string. The author of this question was asking for either removal or settings it to zero. – Melroy van den Berg Apr 02 '23 at 16:18
13

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.

Abhilash
  • 2,026
  • 17
  • 21
10

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.

Jimmy Kane
  • 16,223
  • 11
  • 86
  • 117
  • 5
    This sets the seconds and milliseconds values to 0 but doesnt remove them from the string. – Hanu Aug 10 '18 at 07:08
  • 1
    @Amruta-Pani the op asked to remove OR set them to 0. You can remove with a string strip if needed. – Jimmy Kane Aug 11 '18 at 09:21
4

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()))
ips
  • 111
  • 7
4

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/, "");
mar10
  • 14,320
  • 5
  • 39
  • 64
4

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


To suppress seconds too:

  const now = DateTime.now();
  console.log("now as TS", now.toMillis());
  const x = now.toUTC().set({ millisecond: 0, second: 0 }).toISO({
    includeOffset: true,
    format: "extended"
  });

  console.log("stripped as ISO", x);
  console.log("stripped as TS", DateTime.fromISO(x).toMillis());

Here is an interactive example (CodeSandbox): https://codesandbox.io/s/angry-cerf-gl9nsc?file=/src/index.js

Vadorequest
  • 16,593
  • 24
  • 118
  • 215
disco crazy
  • 31,313
  • 12
  • 80
  • 83
  • You can also use `suppressSeconds` parameter. See https://moment.github.io/luxon/api-docs/index.html#datetimetoiso – Vadorequest Aug 12 '23 at 08:45
2

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>
Sarhanis
  • 1,577
  • 1
  • 12
  • 19
2
let date = new Date();
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());

I hope this works!!

2

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

const date = moment()

// Remove milliseconds

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

// Remove seconds and milliseconds

console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm[Z]'))
Dwight Rodriques
  • 1,382
  • 1
  • 12
  • 11
1

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

aakarsh
  • 21
  • 4
1

Date.prototype.toISOString()

is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively)

Last 8 characters returned from toISOString are always of pattern :ss.sssZ; hence backward slicing may be more elegant:

new Date().toISOString().slice(0, -8) // 2023-04-18T12:23

Now you can add :00.000z if you need to.

ZuzEL
  • 12,768
  • 8
  • 47
  • 68
0

In case for no luck just try this code It is commonly used format in datetime in the SQL and PHP e.g. 2022-12-25 19:13:55

console.log(new Date().toISOString().replace(/^([^T]+)T([^\.]+)(.+)/, "$1 $2") )
ElvinD
  • 667
  • 1
  • 7
  • 10