Home > Net >  Set hour for initial timezone of the date in javascript
Set hour for initial timezone of the date in javascript

Time:10-26

If I receive the following date string on the server which has a timezone of 03:00

2022-10-24T00:00:00 05:00

I want to set the hour to something fixed, 8 A.M. let's say, so the result would be

2022-10-24T08:00:00 05:00

which would translate to 2022-10-24T06:00:00 03:00 according the timezone of the server.

How can I achieve this with the Date object or moment, without modifying the string directly? My problem is that if I try to set the hour after creating a date/moment object that will set the hour for the already converted to the server timezone date (2022-10-24T08:00:00 03:00).

CodePudding user response:

I would suggest using luxon for this purpose, moment.js is not recommended for new projects.

It's easy to do with the DateTime.fromISO() method, setting the setZone parameter to true and passing in the original timestamp.

If we log the date now we should see:

2022-10-24T00:00:00.000 05:00

We can then use the set() method to set the hour to 8.

If we log the date now we should see (as expected):

2022-10-24T08:00:00.000 05:00

We can then use DateTime.toLocal() to return to the local or server timezone.

If we log the date now we should see:

2022-10-24T06:00:00.000 03:00

(as long as we're in a timezone that's currently UTC 03:00)

const { DateTime } = luxon; 

let dt = DateTime.fromISO('2022-10-24T00:00:00 05:00', { setZone: true });

console.log('Initial date:'.padEnd(24), dt.toString());

dt = dt.set({ hour: 8 });

console.log('After setting hour:'.padEnd(24), dt.toString());
console.log('After setting to local:'.padEnd(24), dt.toLocal().toString() );
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js" integrity="sha512-6ZJuab/UnRq1muTChgrVxJhSgygmL2GMLVmSJN7pcBEqJ1dWPbqN9CiZ6U3HrcApTIJsLnMgXYBYgtVkJ8fWiw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  • Related