I am making an application in nodejs and dates are a headache.
I'm using moment to control it, but something is failing me. when I do moment().getDate() to get the current datetime this returns the date of the server where it is running and I don't want that. I need to set the Mexico timezone by default, if I am not wrong it is 'America / Mexico_city' I have never done it so reading I found this instruction
moment().utcOffset(-360).format('YYYY-MM-DD HH: mm: ss');
This correctly returns the current date and time to me, but it is a string, and my database model does not accept strings, but Date types. (I am using MongoDB and mongoose) so it makes it incompatible to save.
Tried doing new Date (moment().UtcOffset(-360).format ('YYYY-MM-DD HH: mm: ss')) but it returns back to server date.
I'm a newbie with dates so all suggestions are welcome.
Date in JavaScript is always in milliseconds since 1 January 1970 UTC. moment is a wrapper that makes it easier to parse and manipulate JavaScript dates. It doesn't matter if you use moment to create them, Dates are always in UTC.
When you set the utcOffset on moment, it doesn't change the internal UTC time of moment, it just uses that setting when formatting.
const now = Date.now();
console.log(new Date(now)); // now in UTC formatted in ISO 8601 with special Z time zone indicator
console.log(moment(now).format()); // now in UTC formatted in ISO 8601 with offset time zone indicator set to the current system's time zone offset.
console.log(moment(now).utcOffset(-360).format()); // now in UTC formatted in ISO 8601 with offset time zone indicator set to UTC-6:00.
console.log(moment(now).utcOffset(-360).format('LLLL')); // now in UTC formatted with your locale settings set to UTC-6:00.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
None of the utcOffset or formatting methods change the underlying Date used by moment.
When you save a Date to your DB it will be in UTC. You will have to use moment (or some other formatter) to display it in the time zone you want. The database does not save the time in an ambiguous non-time zone aware way. Nor will it store specific time zone information with your date.
You could use date math to subtract your offset to the UTC Date, but you would still save in UTC -- just 6 hours earlier. Then you'd have to add those hours when you pulled it from the DB. If you do this and just display the raw date from the DB without adding the hours back, you'll see the "Z" time zone indicator. This would be really confusing.
You could also save your date as a string in the DB. This would enable you to save a formatted date with time zone information. Then you will have to convert it back to a date to do any additional parsing, formatting, math, or validation.