skip to Main Content

Original code

const start = new Date();

console.log(start);

Result

2023-12-14T20:11:12.388Z

My timezone is America/New_York, 5 hours behind UTC.

Question

How should i convert a new Date object in the format of?

2023-12-14T15:11:12-05:00

I’ve been trying things like this but no luck yet,

const dateFormat = new Intl.DateTimeFormat("en-US", {
  timeZone: "America/New_York",
  dateStyle: "short",
  timeStyle: "long"
});

console.log(dateFormat);

Either native JS, or date-fns is fine.

5

Answers


  1. Chosen as BEST ANSWER

    Seems formatISO from date-fns works:

    import formatISO from 'date-fns/formatISO';
    
    const start = new Date();
    console.log(formatISO(start));
    

  2. You can use date-fns-tz.

    npm install date-fns-tz

    const { format, utcToZonedTime } = require('date-fns-tz');
    
    const start = new Date();
    const timeZone = 'America/New_York';
    
    const zonedDate = utcToZonedTime(start, timeZone);
    
    const formattedDate = format(zonedDate, "yyyy-MM-dd'T'HH:mm:ssXXX", { timeZone });
    
    console.log(formattedDate);
    
    Login or Signup to reply.
  3. I’m not necessarily thrilled with the fact that JavaScript is somewhat underpowered when it comes to handling dates.

    Solution # 1 (function convertToTimeZone(Date, string): Date)

    If you retrieve the date from your machine and convert it to a specific language’s date, you get the correct time back, but in a textual form. To turn it back into a Date object, you have to redeclare it. The solution is, by the way, native JavaScript, so it might be a bit more practical than installing a complete package just for this.

    function convertToTimeZone(date, targetTimeZone) {
      // Format the date in the desired time zone
      const options = { timeZone: targetTimeZone };
      const formattedDate = date.toLocaleString('en-US', options);
    
      // Convert the formatted date back to a Date object
      const convertedDate = new Date(`${formattedDate} UTC`);
    
      return convertedDate;
    }
    
    // Example: Current date and time
    const currentDateTime = new Date();
    console.log('Current date and time:', currentDateTime);
    
    // Conversion to New York time zone (America/New_York)
    const convertedDateTimeToNewYork = convertToTimeZone(currentDateTime, 'America/New_York');
    console.log('Converted date and time to New York:', convertedDateTimeToNewYork);
    
    // Conversion to Tokio time zone (Asia/Tokyo)
    const convertedDateTimeToTokyo = convertToTimeZone(currentDateTime, 'Asia/Tokyo');
    console.log('Converted date and time to Tokyo:', convertedDateTimeToTokyo);

    Solution # 2 (new Date().toTimeZone(string): Date)

    Alternatively, we have the option to extend the original Date class. While in the solution, I’ll start from the original timestamp, I will declare a new class, this time corresponding to the timestamp but in the desired time zone.

    // Expanding the native JS Date class
    Date.prototype.toTimeZone = function (targetTimeZone) {
      // Retrieve the time in milliseconds
      const timestamp = this.getTime();
    
      // Format the date in the specified time zone
      const formattedDate = this.toLocaleString('en-US', { timeZone: targetTimeZone });
    
      // Create a new Date object with the formatted date
      const targetDate = new Date(`${formattedDate} UTC`);
    
      return targetDate;
    };
    
    // Current date and time
    const currentDateTime = new Date();
    console.log('Current date and time:', currentDateTime);
    
    // Conversion to New York time zone (America/New_York)
    const convertedDateTimeToNewYork = new Date().toTimeZone('America/New_York');
    console.log('Converted date and time to New York:', convertedDateTimeToNewYork);
    
    // Conversion to Tokio time zone (Asia/Tokyo)
    const convertedDateTimeToTokyo = new Date().toTimeZone('Asia/Tokyo');
    console.log('Converted date and time to Tokyo:', convertedDateTimeToTokyo);
    Login or Signup to reply.
  4. You don’t really need to use a library for this.

    You can achieve this simply by:

    • Grabbing the ISO string
    • Removing some bits (milliseconds and Zulu) off the end
    • Appending the offset formatted (formatted in HH:MM)
    const now = new Date();
    
    // YYYY-MM-DD'T'HH:mm:ss'[+-]'HH:MM
    console.log(formatDateInIsoWithTimeZone(now));
    
    function formatDateInIsoWithTimeZone(date) {
      return date.toISOString().replace(/(.d{3})?Z$/, '') + formatOffset(now);
    }
    
    function formatOffset(date) {
      const
        offsetInMinutes = date.getTimezoneOffset(),
        sign = offsetInMinutes > 0 ? '-' : '+',
        offset = Math.abs(offsetInMinutes),
        hours = Math.floor(offset / 60).toString().padStart(2, '0'),
        minutes = (offset % 60).toString().padStart(2, '0');
      return `${sign}${hours}:${minutes}`;
    }
    Login or Signup to reply.
  5. const date = new Date();
    const options = {
      timeZone: "America/New_York",
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit', 
      hour: '2-digit', 
      minute: '2-digit', 
      second: '2-digit', 
      timeZoneName: 'longOffset'
    };
    const dateString = date.toLocaleString('sv-SE', options).replace(' ', 'T').replace(' GMT', '');
    console.log(dateString);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search