Working with date/time

I have a netlify function that i need to do some simple date/time manipulation and date/time confuses me a bit.

My assumption is when you run new Date() in production it will return date/time in UTC.

I need to be able to be able to convert that to a string in “YYYY-MM-DD HH:00:00” format un a specific timezone (us-EN; Amireca/Chicago) because the service I am rtying to intract with works with that time not UTC.

I am ooking for the simplest way to do this, seems like it shouldnt be that difficult. I tried .toLocalString but I doesnt produce the proper output format and I cant seem to adjust the output.

okay, maybe i figure it out. what i am doing is the following.

// getting the current time, i believe this will return UTC when in production.
const d = new Date();
// converting that to the needed timezone.
const l = new Date(d.toLocalString(‘en-US’, { timeZone: ‘America/Chicago’ }));
// convert it to the string format needed.
const s = l.getFullYear() + ‘-’ + l.getMonth() + ‘-’ + l.getDate() + ’ ’ + l.getHours() + ‘:00:00’;

When I test it locally it does produce the right output, but i also happen to be in the timezone that i need so the initial new.Date() gives me the correct time to begin with.

Okay, that did not work. what i ended up doing was.

// get current date/time, again it is my assumption this will be UTC time.
const d = new Date();
//convert to string format needed, removing the “,” that get inserted between date and time
const s = d.toLocaleString(‘en-CA’, { timeZone: ‘America/Chicago’, hour12: false}).replace(/,/g, ‘’)

Seems to work, I used ‘en-CA’ becasue that gave me YYYY-MM-DD using ‘en-US’ gave me mm/dd/yyy. Anyway I hope this still works with ‘America/Chicago’ as the time zone and dosnt give me any issues.

1 Like

Hiya @jeff-taste, thank you for coming to the forums! We are so glad you are here. I’m glad to hear you were able to resolve your issue. Thanks for coming back and notifying us. This will help many other people who encounter similar problems in the future. Happy building! :netliconfetti: :wave:t6: