Date.now() to local time without creating a date object

Date.now() gives me a UTC Unixtime in ms. Is there a way to convert it to a locale-based string without creating a Date object? All the functions of Date objects like toLocaleString() do work on Date objects, of course. I basically think of something like a class function instead of an object method.

I’m not sure why you’d not want to use a Date object. Can you give me some more information?

Would https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date be helpful at all? Could you get the value entered into there, and put out the localized time?

When you say “class function”, are you thinking of some kind of custom method? Off the top of my head, you’d probably want to do something like take the unixtime value and subtract (or add) the difference in MS between UTC and the time at your locale.

I read several recommendations that it is good practise to avoid creating a object wherever possible for overhead reason (e.g. GC)
right now I create Date objects just to generate the corresponding toISOString that I want to have (including local time offset). Something like
get_Local_ISO_String(Date.now(),timezone_offset) is what I am looking for

It is a good practice for different purposes. But remember “premature optimization is the root of all evil” ;-)…

you could keep a date object and do

var event = new Date();

// and call repetively later in the program
event.setTime(Date.now());

But I am far from certain that this would be a good idea.

1 Like