Home > Software design >  Adding "HH:MM" time format to Date Object Javascript properly
Adding "HH:MM" time format to Date Object Javascript properly

Time:11-16

I have the requirement to set particular time of the day to Date Object. The Time is in String and is CET, so "16:00" means "15:00" in UTC in Winter time. The following code does the job in node.js on my local machine which is in CET Timezone:

addTimetoDate(new Date(),"16:00");

function addTimetoDate(theDate,theTime){
    var dtDate = new Date(theDate)
   try{
    var strTime = theTime.replace(/ /g,'');
    var hourArray = strTime.split(":");
    dtDate.setHours(parseInt(hourArray[0]), parseInt(hourArray[1]), 0)
    
    if (dtDate == "Invalid Date"){
        dtDate = theDate;
    }

   } catch (e){
        dtDate = theDate;
    }
    return dtDate
}

However when deployed to remote server it produces Date Object which is offset by one hour the other direction when displayed with toLocaleString it shows "17:00". How to do it elegant way (as simple deduction of one hour will work only in Winter Time.

CodePudding user response:

toLocaleString will convert the given time into the timezone defined by the locale,... and that's fine if the time is UTC to start with. But if it's already been offset, then it's going to offset it again, which is what you're seeing.

Time is a fiddly creature; when I'm working with time I always store it (eg in a database) as UTC and let the client descide how it gets displayed. That way I can guarantee no server-side silliness.

CodePudding user response:

If your date is a string then append the timezone offset to it as shown and use that to create a date object. It will be stored as UTC and can be used to display any timezone you want, including CET. If you only need the time part then use toLocaleTimeString()

See related question: How to initialize a JavaScript Date to a particular time zone

If you need something more there are libraries like Luxon and Day.js, but avoid the depreciated Moment.js library.

  var d = new Date("2022-11-15T15:00:00.000 01:00");
  
  
  console.log( 
    d.toLocaleString('de-DE', { timezone: 'Europe/Berlin' }), // CET
    d.toLocaleString('en-UK', { timeZone: 'Europe/London' }),
    d.toLocaleString('en-US', { timeZone: 'America/New_York' })
  );

  • Related