Liv
Liv

Reputation: 15

Converting Formatted Date String Using toLocaleString Method To Timestamp Using Javascript

I need to convert datetime html input data to a timestamp after I have used the toLocaleString method to format the date's time zone.

HTML

<input
  type="datetime-local"
  class="form-control my-2"
  id="dateTime"
/>

Javascript

const dateTimeInput = document.querySelector("#dateTime") 
// Output Example: 2022-08-02T13:32

const date = new Date(dateTimeInput.value).toLocaleString('en-CA', {
    timeZone: 'Canada/Eastern',
}) 
// Output: Tuesday, August 2, 2022 at 07:32:00 Eastern Daylight Saving Time

I've tried using the getTime() method after using toLocaleString

How do I convert my formatted date and time string to a timestamp (in milliseconds) after setting the timezone of the date?

Upvotes: 1

Views: 847

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241485

As I mentioned in comments, one can't ask for a Unix Timestamp in terms of another time zone because Unix Timestamps are always in terms of UTC.

However, you can interpret the input value in another time zone, and obtain a UTC-based Unix Timestamp from that. I think that's what you're asking for.

Unfortunately, JavaScript can't do this by itself yet. The Temporal proposal will be adding better support for time zones, but until that is widely available you will need to us a library to handle the conversion. I'll use Luxon in this example, but there are others.

const dateTimeInput = document.querySelector("#dateTime");
const timeZone = 'America/Toronto';

dateTimeInput.addEventListener('change', () => {
  
  // This creates a Luxon.DateTime object from the given inputs
  const dateTime = luxon.DateTime.fromISO(dateTimeInput.value, {
      zone: timeZone
  });

  // And here we can output some values from that
  console.clear();
  console.log('Original Input:', dateTimeInput.value);
  console.log(`Assigned to ${timeZone}:` , dateTime.toString());
  console.log('As a Unix Timestamp (ms):', dateTime.toMillis());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js"></script>
<input type="datetime-local" id="dateTime" />

Also note I used America/Toronto, which is the canonical form of Canada/Eastern, but either would work.

Upvotes: 1

Related Questions