skip to Main Content

Is it possible to create a JavaScript function that returns unix timestamp of beginning of the day for a given date and timezone ? If yes how ?

This is not about just converting a date string to a timestamp. It must take timezone in to the account.

I have made many attempts and failed.

Eg –

getMidnightTimestamp('2023-04-10','Australia/Sydney');

This is what I have tried but it returns invalid timestamps for some reason.

 function getMidnightTimestamp(date, timezone) {
    // Parse the input date
    const inputDate = new Date(date);

    // Set the input date to midnight
    inputDate.setHours(0, 0, 0, 0);

    // Create an Intl.DateTimeFormat object with the given timezone
    const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
        timeZone: timezone,
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
    });

    // Format the input date to a string in the specified timezone
    const dateString = dateTimeFormat.format(inputDate);

    // Parse the formatted date string back to a Date object
    const midnightDate = new Date(dateString);

    // Return the timestamp in milliseconds
    return midnightDate.getTime()/1000;
}

console.log(getMidnightTimestamp('2023-04-10','Australia/Sydney'));

2

Answers


  1. You can try to parse the timezone info using Date.prototype.toLocaleString() method:

    function getMidnightTimestamp(date, timeZone) {
      // We first try to create it using UTC timezone just to obtain the correct timezone info that includes DST
      const rawOffset = new Date(`${date}T00:00:00.000+00:00`)
        .toLocaleString('en-US', {
          timeZone,
          timeZoneName: 'shortOffset'
        })
        .split('GMT')[1]; // Then we parse the timezone info using the back of the generated string such as GMT+12:45
      const sign = rawOffset[0] || '+';
      const [hour = '', minute = ''] = rawOffset.substring(1).split(':');
      // Lastly we construct the full ISO date string to obtain the midnight Date / timezone for that region
      const midnightDate = new Date(`${date}T00:00:00.000${sign}${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`);
      return midnightDate.getTime() / 1000;
    }
    
    // Sample
    console.log(getMidnightTimestamp('2023-04-10','Australia/Sydney'));
    Login or Signup to reply.
  2. due to MDN

    JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the epoch).

    So, you should just set the time based on the specified timezone and convert it into a number; by default, it will be converted to UNIX timestamp format.

    and here is the code :

    
    function getMidnightTimestamp (date, timeZone) {
      
      let date$ = new Date( date );
    
      date$ = new Date( date$.toLocaleString("en-US",{timeZone}) )
    
      return Number( date$ ) / 1000; // we divided by 1000 because it returns the UNIX timestamp in milliseconds and the standard is seconds-based format
      
    }
    
    const timestamp = getMidnightTimestamp('2023-04-10','Australia/Sydney');
    
    console.log(timestamp);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search