Home > front end >  How to convert UK DateTime to GMT time in angular
How to convert UK DateTime to GMT time in angular

Time:08-08

I am working on a angular project.

I want to the start time and off time of a office in a table.

Example : 8:30 - 17:30

The office has two branches in UK and India.

So user may enter time in UK time or Indian time. But I am going to store the time in GMT time.

SO I want to give an option to select the time zone and enter the time.

Then I have to convert then that time into GMT time and send to database.

How can I convert UK time to GMT time?

Or do you know any idea to do this scenario Please advice me.

Thank you

CodePudding user response:

why not store it in Epoch Time and convert it every time? like 1659755549? or use epoch as intermediate for calculation

p.s. no rep for comments :(

CodePudding user response:

ECMAScript Date instances don't have a timezone, they are inherently UTC. System settings are used for default toString plus get and set methods so they appear to be local.

Also, the parser is very basic and is generally to be avoided other than for parsing the exact format specified for toISOString.

You should also see How to initialize a JavaScript Date to a particular time zone, which might be a duplicate for this question.

The best way to achieve what you're after (until the Temporal object is widely supported) is to use a library. There are a number of libraries that work with timezones, the following uses Luxon.

// Alias
let DateTime = luxon.DateTime;

// Create a date for now in London
let ukDate = DateTime.now().setZone('Europe/London');

// Set it to the required time
let ukOpenTime = ukDate.set({hour:8, minute:30, second:0, millisecond: 0});
console.log('ukOpenTime as string    :'   ukOpenTime.toString());

// Get time value to store
let millis = ukOpenTime.toMillis();
console.log('ukOpenTime as time value: '   millis);

// Show equivalent local time in numerous ways
// Shift ukOpenTime to local zone: default is the local (system) timezone
let localOpenTime = ukOpenTime.setZone();
console.log('Equivalent local time 1 : '   localOpenTime.toString());

// Use the time value (millis) to create a new Luxon object
let localOpenTime2 = DateTime.fromMillis(millis);
console.log('Equivalent local time 2 : '   localOpenTime2.toString());

// Use the time value (millis) to create a plain date
let localOpenTime3 = new Date(millis);
console.log('Equivalent local time 3 : '   localOpenTime3.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js"></script>

  • Related