-3

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'));
E_net4
  • 27,810
  • 13
  • 101
  • 139
M_R_K
  • 5,929
  • 1
  • 39
  • 40
  • [I downvoted because no attempt was made](https://idownvotedbecau.se/noattempt/). The [tour] contains _"Don't ask about... Questions you haven't tried to find an answer for (show your work!)"_. The tooltip of the downvote button contains _"This question does not show any research effort"_. – jabaa Apr 27 '23 at 01:20
  • 1
    `1681077600000` is the number of milliseconds. A Unix timestamp is the number of seconds. Divide by 1000. – jabaa Apr 27 '23 at 01:32
  • @jabaa No it does not answer my question. – M_R_K Apr 27 '23 at 01:36
  • Does this answer your question? [Check midnight in a specific time zone node js](https://stackoverflow.com/questions/71249018/check-midnight-in-a-specific-time-zone-node-js) – pejalo Jul 19 '23 at 13:12
  • @pejalo No. Any of those NodeJS solutions did not work in the browser. – M_R_K Jul 19 '23 at 23:12
  • See this answer: https://stackoverflow.com/a/72560808/4621566 – pejalo Jul 20 '23 at 05:25
  • idownvotedbecau.se is rubbish - "https://idownvotedbecau.se/noattempt/" It is funny how toxic community of SO came up with their own rules and guidelines. StackOverflow never says you cannot ask a question without making an attempt ! – M_R_K Jul 24 '23 at 01:53
  • _"Don't ask about... Questions you haven't tried to find an answer for (show your work!)"_ [tour] Maybe after these years you should reread the tour. – jabaa Jul 24 '23 at 06:51

2 Answers2

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'));
AngYC
  • 3,051
  • 6
  • 20
  • 1681048800000 isn't a Unix timestamp in this century. – jabaa Apr 27 '23 at 01:35
  • @jabaa It is UNIX timestamp in milliseconds. :) – M_R_K Apr 27 '23 at 01:35
  • @M_R_K There is no such thing as a Unix timestamp in milliseconds. A Unix timestamp is in seconds by definition. 1681048800000 is the number of milliseconds since epoch. – jabaa Apr 27 '23 at 01:36
  • @jabaa Yes there is such a thing of course. Javascript generally output UNIX timestamp in milliseconds unless you divide it by 1000. – M_R_K Apr 27 '23 at 01:39
  • 1
    Hi @jabaa and @M_R_K, that's my bad, I can fix it by `/ 1000`, let me modify the code – AngYC Apr 27 '23 at 01:39
  • This is a clever approach, but not guaranteed to work 100% of the time. The `Date()` constructor is called twice in this code snippet, each representing a different point in time: a) midnight UTC and b) (probably) midnight in the desired timezone. This approach will only work when the desired timezone's offset does not change between (a) and the actual midnight of the desired timezone. In other words, if daylight savings happens to come in/out of effect within this narrow window, it will cause a bug. – pejalo Jul 19 '23 at 12:45
0

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);