Search code examples
javascriptangularluxon

Angular/Javascript Luxon - Convert timestamp changing time to current user timezone


I got a timestamp from the database and I need to display its time in the user's timezone.

Ex: Brazil 16:42, France 21:42.

It's a chat, so the messages need to be displayed in each user's time zone.

I have luxon in the project, but I can not use any of the documentation that helps me in this case.

I have tried to use the methods in some ways

DateTime.local() and DateTime.setZone(localZone)

localZone is a variable that receives the local area, for example: "Europe/Paris".

Thank you!


Solution

  • You can simply use luxon fromMillis to parse timestamp (assuming that it is in milliseconds) or fromSeconds if it is in seconds. You can also pass zone option to create luxon object using given timezone. The you can use toFormat() to display time in your desired format. You could have something like the following:

    DateTime.fromMillis(timestamp, {zone: localZone}).toFormat('HH:mm')
    

    If you need, you can also use setZone to change zone property, here a snippet using sample data:

    const DateTime = luxon.DateTime;
    let curTimestamp = 1562061791000;
    let time = DateTime.fromMillis(curTimestamp)
    console.log('Local time:', time.toFormat('HH:mm') );
    console.log('Brazil time:',  time.setZone('America/Sao_Paulo').toFormat('HH:mm') );
    console.log('France time:', DateTime.fromMillis(curTimestamp, {zone: 'Europe/Paris'}).toFormat('HH:mm') );
    <script src="https://cdn.jsdelivr.net/npm/luxon@1.16.0/build/global/luxon.js"></script>

    If you want to use Luxon inside Angular view have a look to luxon-angular.