Locale specific date without year - javascript

I am using https://github.com/abritinthebay/datejs/ for date formatting due to locale support. However, is it not possible to get a full date time without year?
Example
Input date:2014/09/20 20:00:00
Output date: 09/20 20:00
And it has to respect locale settings!

Looks like since ES2015 you can just skip first parameter and set only 'options' parameter, in that way locale will be applied:
new Date().toLocaleString(undefined, {
month: "short", day: "numeric",
hour: "numeric", minute: "numeric", second: "numeric"
}) // "Jul 11, 5:50:09 PM"
I didn't find the way to remove comma between date and time. For that case string formatting can be used:
const dateTime = new Date();
const datePart = dateTime.toLocaleDateString(undefined, {month: "short", day: "numeric"});
const timePart = dateTime.toLocaleTimeString();
const result = `${datePart} ${timePart}`;
// "Jul 11 5:57:10 PM"

console.log(new Date().toLocaleString('en-En',{weekday: "long", month: "long", day: "numeric"}))
You can change this options as you want.

To format a date as month/day hour:minute with Date.js you'd call toString with the format 'MM/DD HH:mm' to get two digits for all values, e.g.:
console.log(new Date().toString('MM/dd HH:mm'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
Attempting to determine the format that the user expects to see is very problematic, whether it's referred to as "culture", "locale" or just "preference". Javascript doesn't have access to system settings and the browser doesn't reveal them. You can try to guess based on the output of Date.prototype.toLocaleString, but that is entirely implementation dependent and doesn't necessarily conform to user preferences.
One common approach is to use an unambiguous format so user preferences don't matter, e.g.
console.log(new Date().toString('dd-MMM HH:mm'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
Another approach is to have an unambiguous default format, then allow the user to select from a few supported formats and store the preference.
There is also the built–in Date.prototype.toLocaleString, which is pretty unreliable but some browsers support the optional ECMA-402 Intl formatting options. It's pretty ordinary as a formatter so really can't be recommended when there are libraries that do the job so much better, e.g.
var options = {
month: 'short',
day : '2-digit',
hour : '2-digit',
minute:'2-digit'
};
// Browser dependent, something like en-us: Jan 21, 8:39 AM
console.log('en-us: ' + new Date().toLocaleString('en-us',options))
// Browser dependent, something like en-gb: 21 Jan, 08:39
console.log('en-gb: ' + new Date().toLocaleString('en-gb',options))
Yet another approach is to write your own parser and formatter that does just what you need. If you only need to support one or two formats, it's pretty straight forward, e.g.
// input format yyyy/mm/dd hh:mm:ss
function parseDateString(ds) {
var d = ds.split(/\D+/);
return new Date(d[0], --d[1], d[2], d[3], d[4], d[5]);
}
// Return date string as mm/dd hh:mm
function formatDate(d) {
function z(n) {
return (n < 10 ? '0' : '') + n
}
return z(d.getMonth() + 1) + '/' + z(d.getDate()) +
' ' + z(d.getHours()) + ':' + z(d.getMinutes());
}
console.log(formatDate(parseDateString('2014/09/20 20:00:00'))); // 09/20 20:00
So you can replace an entire library with less than a dozen lines of code. :-)

Related

JavaScript Intl/BCP 47: How to use ISO date format `yyyy-mm-dd` for German locales instead of `dd.mm.yyyy`?

Germany uses two different date formats:
modern (not used very often, ISO-8601): 2022-01-31
classical (used by most Germans): 31.01.2022
JavaScript's Intl API uses the "classical" date format for locale de-DE:
// This prints out: 31.01.2022
console.log(new Intl.DateTimeFormat('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).format(new Date(2022, 0, 31)));
Please find here the demo: » Demo
Is it somehow possible to use the "modern" (= ISO-8601) date format with Intl by just extending the locale in the example above ('de-DE...')? Using the locale de-DE-u-ca-iso8601 for example is not working.
BTW: Using Date.prototype.toISOString is NOT an option.
[Edit] It's also NOT an option to just use a locale for a different country.
[Edit] I hoped to find a answer somewhere here or here, but have not found a solution there.
[Edit] You can configure the time format by the locale string:
en-GB (shows 24 hour time format)
en-GB-u-hc-h12 (shows 12 hour time format, adding am/pm)
... so I hoped something similar to this would also be possible with 'dd.mm.yyyy' vs 'yyyy-mm-dd'.
Use en-CA as locale.
Afaik there is no specific locale to format into the 'modern' (iso) date string.
Either split and reorder the date string, use formatToParts instead of format or split the result of Date.toISOString may be other ideas.
// 1. locale 'en-CA' (not an option as per comment)
console.log(new Intl.DateTimeFormat(`en-CA`, {
year: `numeric`, month: `2-digit`, day: `2-digit`})
.format(new Date(2022, 0, 31)));
// 2. split and reorder the result
console.log(new Intl.DateTimeFormat(`de-DE`, {
year: `numeric`, month: `2-digit`, day: `2-digit`})
.format(new Date(2022, 0, 31))
.split(`.`)
.reverse()
.join(`-`) );
// 3. use formatToParts
const reformatGerman = new Intl.DateTimeFormat(`de-DE`, {
year: 'numeric', month: '2-digit', day: '2-digit'})
.formatToParts(new Date(2022, 0, 31))
.filter( v => ~[`year`, `month`, `day`].indexOf(v.type) )
.reduce( (acc, val) => ({...acc, [val.type]: val.value}), {} );
console.log(`${
reformatGerman.year}-${
reformatGerman.month}-${
reformatGerman.day}`);
// 4. truncate the result of `toISOString()`
console.log(new Date(Date.UTC(2022, 0, 31))
.toISOString().split(`T`)[0]);

How do I convert certain Date object to the corresponding time in germany? [duplicate]

This question already has answers here:
Convert date to another timezone in JavaScript
(34 answers)
Closed 2 years ago.
Let's say I have a Date object like this:
let dateToConvert = new Date(date_string) // represents certain time like 12th Aug 11PM in India
What I want to achieve is to design a function like this:
getGermanDate(dateToConvert): Date {
// What should be written here?
}
The function should return Date object that is the time in Germany at the time that is in dateToConvert object.
Thanks in advance.
Formatting of javascript dates is covered in numerous other questions. A particular timezone can be specified using the timeZone option with toLocaleString or for more control use the Intl.DateTimeFormat constructor and format option (timezones are specified using an IANA representative location to apply historic and DST changes), e.g.
let d = new Date();
// toLocaleString, default format for language de
console.log(d.toLocaleString('de',{timeZone:'Europe/Berlin', timeZoneName: 'long'}));
// DateTimeFormat.format with specific options
let f = new Intl.DateTimeFormat('de', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
hour12: false,
minute: '2-digit',
timeZone: 'Europe/Berlin',
timeZoneName: 'short'
});
console.log(f.format(d));
You might also be interested in this answer.
You could use native JavaScript functions to convert (toLocaleString), or you could use moment timezone (which is more flexible).
For the toLocaleString call I'm also specifying a Germany date format (by passing "de-DE" to the locale parameter, you could use whichever locale you wish.
function getGermanDate(input) {
return moment.tz(input, "Europe/Berlin");
}
/* Using moment timezone */
let timestamp = "2020-08-12 23:00:00";
let timeIndia = moment.tz(timestamp, "Asia/Kolkata");
let timeGermany = getGermanDate(timeIndia);
console.log("Time (India):", timeIndia.format("YYYY-MM-DD HH:mm"));
console.log("Time (Germany):", timeGermany .format("YYYY-MM-DD HH:mm"));
/* Using native JavaScript */
let dateToConvert = new Date("2020-08-12T23:00:00+0530");
console.log("Time (India, native):", dateToConvert.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }));
console.log("Time (Germany, native):", dateToConvert.toLocaleString('de-DE', { timeZone: 'Europe/Berlin' }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.25/moment-timezone-with-data-10-year-range.js"></script>

How to format date into Arabic with English numerals for date and year in JavaScript?

I want the date to be formatted in the following format:
date: 2016-12-04 into الأحد، 4 ديسمبر، 2016
But I'm getting the following. The numbers are converted to Arabic numerals. I want the date and year in English numerals:
الأحد، ٤ ديسمبر، ٢٠١٦
I have used the following code to format the date to Arabic.
var date = new Date('2016-12-04');
options = {
weekday: 'long',
year: 'numeric',
month: 'short',
day: 'numeric',
};
var dateString = date.toLocaleDateString('ar-SA', options);
alert(dateString);
Found a solution Date conversion and manipulation in javascript with Arabic months
My modified code to get my desired output is as follows.
var date = new Date('2016-12-04');
var months = ["يناير", "فبراير", "مارس", "إبريل", "مايو", "يونيو",
"يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"
];
var days = ["اﻷحد", "اﻷثنين", "الثلاثاء", "اﻷربعاء", "الخميس", "الجمعة", "السبت"];
var delDateString = days[date.getDay()] + ', ' + date.getDate() + ' ' + months[date.getMonth()] + ', ' + date.getFullYear();
console.log(delDateString); // Outputs اﻷحد, 4 ديسمبر, 2016
You can use this Locales to specify numbering system.
let date = newDate.toLocaleDateString('ar-EG-u-nu-latn',{weekday: 'long', year: 'numeric', month: 'short', day: 'numeric'});
also check this MDN link to know more about it
A better (safer) way to get the Hijri (Islamic) date in English Numerals (Western-Arabic Numbers) in javascript is NOT to use a specific country locale like "ar-SA" or "ar-TN" or "ar-EG"; but use the Intl.DateTimeFormat() constructor with the following Locale options:
The numbering system (nu) set to latn (i.e. Western-Arabic Numbers), and
Calendar type (ca) set to islamic, and
The language locale to ar
The Locale options can be passed as an array for multiple options: ["ar-u-ca-islamic","ar-u-nu-latn"]
or as one string : "ar-u-ca-islamic-nu-latn"
Here is an example code that will print today's Hijri (Islamic) date with Western-Arabic Numbers (English Numerals):
I have also included a table to give the list of all Arabic "ar" locales and the default outputs to see the difference between them with regards to the name of the months and the default number system.
let options = {day: 'numeric', month: 'long',weekday:'long',year:'numeric'};
// 1st method
let locales = ["ar-u-ca-islamic","ar-u-nu-latn"];
console.log(new Intl.DateTimeFormat(locales, options).format(Date.now()));
// 2nd method
locales = "ar-u-ca-islamic-nu-latn";
console.log(new Intl.DateTimeFormat(locales, options).format(Date.now()));
To get the current hijri date in javascript, we can use Intl.DateTimeFormat
To get the arabic display :
new Intl.DateTimeFormat('ar-TN-u-ca-islamic', {day: 'numeric', month: 'long',weekday: 'long',year : 'numeric'}).format(Date.now());
the expected output :
السبت، 4 صفر 1443 هـ
https://medium.com/#Saf_Bes/get-today-hijri-date-in-javascript-90855d3cd45b
Try 'ar-MA' (for Morocco) instead of 'ar-SA'.

JavaScript full names for day-of-week and month (or How to get the date names per client locale)

The string that is returned from (new Date()).toString() looks something like this:
"Tue Nov 22 2016 14:14:51 GMT-0800 (Pacific Standard Time)"
Is there a built-in method/constructor that we can use that will not abbreviate the day-of-week and/or month? In other words, does JS support this:
"Tuesday November 22 2016 14:14:51 GMT-0800 (Pacific Standard Time)"
The reason for my question is because I'm looking for a lazy/hacky way that we might be able to get the Weekday and Month names in the language of the client.
If you don't need to support old browsers (older than IE 11), you can use toLocalDateString().
Example:
new Date().toLocaleDateString('en-US', {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
})
But moment.js is way more comfortable.
See MDN Date.prototype.toLocaleDateString() for more information.
As Josa's answer implies, it is possible to get the full names for the weekday and month (for most modern browsers).
I used the .toLocaleDateString() to extract the full names of the weekday and month in the language of the client successfully using Chrome and IE11 (it does NOT work in Safari 9).
Extending the idea of getting the full names from the browser, I was curious if we could, then, get the name of the weekday and the name of the month in the language that matches the client's locale. The following experiment shows that that it is possible (although, not reliable).
For Experiment/Fun:
The following function will return an object that includes the name of the Weekday and Month for a particular date in the language of a particular locale-code.
Fiddle
function getWeekdayAndMonthNamesByLocaleCode(localeCode, date) {
var Names = {
Weekday: "",
Month: ""
};
if (!(date instanceof Date && !isNaN(date.valueOf()))) {
date = new Date();
}
if (localeCode == null || localeCode.length < 2) {
localeCode = navigator.language;
}
Names.Month = date.toLocaleDateString(localeCode, {
month: 'long',
});
Names.Weekday = date.toLocaleDateString(localeCode, {
weekday: 'long'
});
return Names;
}
I haven't tested the function for browser compatibility and I certainly wouldn't rely on it to work for all languages, but I thought it was interesting enough to post here for others to experiment with.

Javascript date objects always one day behind [duplicate]

This question already has answers here:
Wrong Date in Javascript
(3 answers)
Closed 6 years ago.
I am trying to convert a date object from the backend db to a string to present on the view, however, when I convert it, the result is always one day behind.
The code:
date = this.props.date;
d = new Date(date)
options = {
month: "long", weekday: "long", year: "numeric",
day: "numeric"
};
dateStr = d.toLocaleDateString("en-us",options)
EDIT examples provided:
Regarding backend structure, the date is inserted into the database via a simple html datepicker form.
Currently, this.props.date, if rendered on the view, will render something like this:
"2016-10-01"
When I use the code above, it would become:
"Friday, September 30, 2016"
Assuming your backend date is in UTC specifically ISO8601 and you want the displayed date to be UTC in en-us language-region.
var date = "2016-10-01";
var parts = date.split('-');
parts[1] -= 1;
var d = new Date(Date.UTC.apply(null, parts));
options = {
month: "long",
weekday: "long",
year: "numeric",
day: "numeric",
timeZone: 'UTC'
};
document.getElementById('out').textContent = d.toLocaleDateString("en-us", options);
<pre id="out"></pre>
Assuming the date is UTC and the Date object handles ISO8601 correctly (some older versions do not) then you could rely on the built in parsing of Date.
var date = "2016-10-01";
var d = new Date(date);
options = {
month: "long",
weekday: "long",
year: "numeric",
day: "numeric",
timeZone: 'UTC'
};
document.getElementById('out').textContent = d.toLocaleDateString("en-us", options);
<pre id="out"></pre>
So all I have done is explicitly set the output to be UTC, otherwise it is using your runtime's default time zone. Worth noting that toLocaleDateString is still in its infancy and can vary across browsers, just like ISO8601 parsing.

Categories

Resources