Home > database >  Initialize javascript Date to noon in "America/New_York"
Initialize javascript Date to noon in "America/New_York"

Time:07-26

I have a timezone as a canonical name from the IANA time zone list (e.g. "America/New_York"). I do not have the GMT value, which varies with Daylight Savings in ways I don't want to have to think about.

I have a time I want in the target time zone, e.g. noon on July 12, 2000.

How do I initialize a javascript Date to that time?

CodePudding user response:

It's best to use a dedicated Date/Time library, such as luxon for this type of conversion.

We create a DateTime object in the desired timezone, then convert to local.

The DateTime object can be converted to a JavaScript Date using .toJSDate().

const { DateTime } = luxon;

const zone = 'America/New_York';
const obj = { year: 2000, month: 7, day: 12, hour: 12 };
const timeInZone = DateTime.fromObject(obj , { zone });
const localtime = timeInZone.toLocal();

console.log('Time in zone:', timeInZone.toString());
console.log('Local time:  ', localtime.toString());
console.log('Local time (JSDate):', localtime.toJSDate().toString());
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js" integrity="sha512-6ZJuab/UnRq1muTChgrVxJhSgygmL2GMLVmSJN7pcBEqJ1dWPbqN9CiZ6U3HrcApTIJsLnMgXYBYgtVkJ8fWiw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

This can be done in vanilla JavaScript but it is much more awkward.

We must search for the corresponding UTC time for the time in the given timezone.

Once we have this we can display in local time.

function convertToLocal(date, timeZone) {
    const dt = Date.parse(toIso(date)   'Z');
    // Test the entire range of offsets
    for(let offsetMinutes = -900; offsetMinutes <= 900; offsetMinutes  = 15) {
        const test = new Date(dt   offsetMinutes * 60000);
        if (toIso(date) === toIso(test, timeZone)) { 
            return test;
        }
    }
}

function toIso(date, timeZone) { 
    const opt = {
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit', 
        fractionalSecondDigits: 3, timeZone
    };
    return new Date(date).toLocaleString('sv', opt).replace(' ', 'T').replace(',', '.');
}

let zone = 'America/New_York'
let timeInZone = '2000-07-12T12:00:00.000';
console.log('Time in zone:', timeInZone);
console.log('Local time:  ', toIso(convertToLocal(timeInZone, zone)));
.as-console-wrapper { max-height: 100% !important; }

  • Related