Using the Temporal.Calendar of the upcoming proposal of the Temporal global Object, the following short function converts between calendar dates (the 18 Calendars recognized in Javascript).
Currently, the output date returned by Temporal.Calendar for other Calendars is in the format (example): '2022-02-25[u-ca=persian]'
How to avoid usingtoString().split("[")[0])
to get the calendar date without the suffix [u-ca=CalendarName]
as the Intl.DateTimeFormat()
does not recognize the suffix?
<script type='module'>
// ====== load Temporray polyfill (not needed after full Temporal implementation) ========
import * as TemporalModule from 'https://cdn.jsdelivr.net/npm/@js-temporal/polyfill@0.3.0/dist/index.umd.js'
//=====================================================================
// Y,M,D are the date to convert from
// options as in Intl.DateTimeFormat() with additional 'from' and 'locale'
// 'from': calendar name to convert from
// 'locale' the locale to use (default 'en')
// 'calendar': calendar to convert to
// All other options as in Intl.DateTimeFormat()
//---------------------------------------
function dateToCalendars(Y, M, D, op={}) {
return new Intl.DateTimeFormat(op.locale??="en",op).format(new Date(temporal.Temporal.PlainDateTime.from({year:Y,month:M,day:D,calendar:op.from??= "gregory"}).toString().split("[")[0]));
}
//---------------------------------------
//===============================
// Example Test Cases
//===============================
console.log(dateToCalendars(2022,2,25)); // default Gregory
// full format Gregory
console.log(dateToCalendars(2022,2,25, {dateStyle: "full"}));
// from Persian to Gregory in full format
console.log(dateToCalendars(1400,12,6,{from: 'persian', dateStyle: "full"}));
// from Persian to Gregory in full format in 'fa' locale
console.log(dateToCalendars(1400,12,6,{from: 'persian', dateStyle: "full", locale: "fa"}));
// from Persian to Islamic in full format in 'fa' locale
console.log(dateToCalendars(1400,12,6,{from: 'persian', calendar: 'islamic', dateStyle:"full", locale: "fa"}));
// from Islamic to Gregory full format (default 'en' locale)
console.log(dateToCalendars(1443,7,24,{from:"islamic", dateStyle:"full"}));
// from Hebrew to Islamic in full format
console.log(dateToCalendars(5782,6,24,{from: 'hebrew', calendar:"islamic", dateStyle:"full"}));
// from Hebrew to Islamic in full format in 'ar' locale
console.log(dateToCalendars(5782,6,24,{from: 'hebrew', calendar:"islamic", dateStyle:"full", locale: 'ar'}));
// from Hebrew to Persian in full format
console.log(dateToCalendars(5782,6,24,{from: 'hebrew', calendar:"persian", dateStyle:"full"}));
// from Hebrew to Gregory in full format in 'he' locale
console.log(dateToCalendars(5782,6,24,{from: 'hebrew', dateStyle:"full", locale: 'he'}));
</script>