Remove Seconds/ Milliseconds from Date convert to ISO String
Asked Answered
C

13

74

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'
Counterrevolution answered 2/3, 2016 at 21:58 Comment(0)
A
58

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/

Amend answered 2/3, 2016 at 22:1 Comment(6)
there is no need to use moment for such simple date things :) moment is officially legacy: momentjs.com/docsChristology
@Christology Yes I know, but this was 2016Amend
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:00Dramatic
Because I have a +02:00 hours different in UTC. I use: .replace(/\.\d+\+/,'+') to get right of the milliseconds.. It's not pretty.Dramatic
@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.Amend
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.Dramatic
H
66

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.

Homestretch answered 2/3, 2016 at 23:27 Comment(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.Paediatrician
@wuno—wouldn't that be great? Unfortunately ECMAScript Date objects have no formatting support at all, absolutely none. There is the Intl.DateTimeFormat supported by Date.prototype.toLocaleString for some browsers, but it's not definitive in specifying the result. A good parsing and formatting library is fecha.js.Homestretch
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!Paediatrician
@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.Homestretch
this one is perfect for meKiele
Thanks, @RobG! .replace(/\.\d+Z/,'') did the trick for me to remove milliseconds and timezone altogether.Rhomboid
A
58

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/

Amend answered 2/3, 2016 at 22:1 Comment(6)
there is no need to use moment for such simple date things :) moment is officially legacy: momentjs.com/docsChristology
@Christology Yes I know, but this was 2016Amend
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:00Dramatic
Because I have a +02:00 hours different in UTC. I use: .replace(/\.\d+\+/,'+') to get right of the milliseconds.. It's not pretty.Dramatic
@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.Amend
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.Dramatic
U
14

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.

Unscramble answered 5/8, 2020 at 14:44 Comment(0)
V
9

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.

Vinaigrette answered 25/2, 2018 at 18:3 Comment(2)
This sets the seconds and milliseconds values to 0 but doesnt remove them from the string.Onlybegotten
@Amruta-Pani the op asked to remove OR set them to 0. You can remove with a string strip if needed.Vinaigrette
G
6

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

Guardado answered 6/5, 2022 at 14:20 Comment(1)
You can also use suppressSeconds parameter. See moment.github.io/luxon/api-docs/index.html#datetimetoisoRedfield
F
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()))
Finalism answered 7/12, 2016 at 14:44 Comment(0)
A
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/, "");
Ammadas answered 25/7, 2020 at 15:52 Comment(0)
T
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>
Tote answered 2/3, 2016 at 22:7 Comment(0)
G
2
let date = new Date();
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());

I hope this works!!

Gametogenesis answered 23/5, 2019 at 12:55 Comment(0)
H
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]'))
Haswell answered 16/5, 2022 at 21:56 Comment(0)
D
2

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.

Diphase answered 18/4, 2023 at 12:32 Comment(0)
C
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

Cheque answered 15/1, 2020 at 19:48 Comment(0)
M
1

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") )
Mina answered 25/12, 2022 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.