Luxon - set milliseconds for toISO()
Asked Answered
D

3

10

I'm using the following to get the end of day for a date coming from a date picker:

var date = DateTime.fromISO('2018-05-05').endOf('day');

What I want to end up with is

"2018-05-05T23:59:59+02:00"

however, I cannot get rid of the milliseconds:

console.log(date.toISO({suppressMilliseconds: true}));
// => outputs "2018-05-05T23:59:59.999+02:00"

Is there a more elegant way to do this besides simply setting the millisecond to 0:

date.c.millisecond = 0;
console.log(date.toISO({suppressMilliseconds: true}));
// => outputs "2018-05-05T23:59:59+02:00"
Discourse answered 8/3, 2018 at 10:57 Comment(0)
M
15

Right, suppressMilliseconds only applies if they're 0. (See here).

But there's a much easier way to round down the second:

DateTime.fromISO('2018-05-05')
  .endOf('day')
  .startOf('second')
  .toISO({ suppressMilliseconds: true })

You should never mutate the Luxon object like in your workaround.

Miniature answered 13/3, 2018 at 21:17 Comment(0)
V
7
const { DateTime } = require("luxon");
let time = DateTime.now().set({milliseconds: 0});
time = time.toISO({suppressMilliseconds: true});
console.log(time);

It should help and solve the problem.

Volin answered 31/3, 2021 at 13:46 Comment(1)
The OP asks about the end of the day, your variation is working with now(). There is an accepted answer and its pretty much fulfilling the task.Fayth
H
0

The way I did :

DateTime.now().toISO().replace(/\.\d{0,3}/, "");

Using RegExp to remove the "." and millis I was having

2021-02-22T18:03:29.519Z

With the replace RegExp

2021-02-22T18:05:44Z

Hotheaded answered 22/2, 2021 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.