Tolocalestring to date javascript

How to format dates with vanilla JavaScript

A lot of JavaScript developers reach for a library like date-fns when working with dates in JavaScript. Although a library like date-fns provides a lot of functionality, you may not even need it. For example, you can use the built-in JavaScript Date method toLocaleString() to format a timestamp like 2022-03-21T14:18:40.360+00:00 from MongoDB into a readable format like Monday, March 21, 2022 .

In this lesson, we’ll cover the toLocaleString method and write our own utility function to convert timestamps into a readable format.

Watch lesson

toLocaleString overview

The toLocaleString() method is only available on the Date object. Therefore, you will need to convert a timestamp from your database into a Date object before calling the method like so:

const time = '2022-03-24T17:12:40+00:00' // ISO 8601 const convertedTime = new Date(time)

The toLocaleString() method returns a string and accepts two arguments: a locale string and an options object.

The locale string is a BCP 47 language tag that sets a language-sensitive format convention for the date. For example, by setting the value to en-us the date will be formatted for English speakers in the United States. The default language for the browser will be used if you do not pass the locale string into the function.

Читайте также:  Java net urlclassloader addurl

Below you can see the output for a timestamp when only passing in the locale argument:

const time = '2022-03-24T17:12:40+00:00' // ISO 8601 const convertedTime = new Date(time).toLocaleString('en-us') console.log(convertedTime) // "3/24/2022, 1:12:40 PM"

The options object is where you’ll convert a time into the desired readable format. The Mozilla DateTimeFormat documentation outlines all the possible values that you can use with the toLocaleString() method.

Below are some examples of different formatting options and outputs:

const time = '2022-03-24T17:12:40+00:00' // ISO 8601 const convertedTimeOne = new Date(time).toLocaleString('en-us', < year: 'numeric', month: 'long', day: 'numeric', >) console.log(convertedTimeOne) // "March 24, 2022" const convertedTimeTwo = new Date(time).toLocaleString('en-us', < year: '2-digit', month: 'short', day: '2-digit', weekday: 'short', >) console.log(convertedTimeTwo) // "Thu, Mar 24, 22" const convertedTimeThree = new Date(time).toLocaleString('en-us', < year: 'numeric', month: 'short', day: '2-digit', weekday: 'long', hour: '2-digit', minute: '2-digit', timeZoneName: 'short', >) console.log(convertedTimeThree) // "Thursday, Mar 24, 2022, 01:12 PM EDT"

convertTime function

Now that you have a grasp of how the toLocaleString() method works, let’s write a utility function that you can use throughout your project to convert times into your desired format:

const convertTime = time => < return new Date(time).toLocaleDateString('en-us', < year: 'numeric', month: 'long', day: 'numeric', >) >

This function takes one argument, time , which is the timestamp that comes from our database. Then the function converts the time variable into a new Date object before calling the toLocaleString() method.

The locale string is set to en-us and the options are set to return the year formatted as 2022 , the month formatted as March , and the day formatted as 21 .

Conclusion

If your application only requires simple date formatting you may be fine with vanilla JavaScript and the built-in toLocaleString() method. Otherwise, turn to the date-fns library for extra functionality.

Источник

Date.prototype.toLocaleString()

The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat .

Try it

Syntax

toLocaleString() toLocaleString(locales) toLocaleString(locales, options) 

Parameters

The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.DateTimeFormat API, these parameters correspond exactly to the Intl.DateTimeFormat() constructor’s parameters. Implementations without Intl.DateTimeFormat support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the locales parameter of the Intl.DateTimeFormat() constructor.

In implementations without Intl.DateTimeFormat support, this parameter is ignored and the host’s locale is usually used.

An object adjusting the output format. Corresponds to the options parameter of the Intl.DateTimeFormat() constructor. If weekday , year , month , day , dayPeriod , hour , minute , second , and fractionalSecondDigits are all undefined, then year , month , day , hour , minute , second will be set to «numeric» .

In implementations without Intl.DateTimeFormat support, this parameter is ignored.

See the Intl.DateTimeFormat() constructor for details on these parameters and how to use them.

Return value

A string representing the given date according to language-specific conventions.

In implementations with Intl.DateTimeFormat , this is equivalent to new Intl.DateTimeFormat(locales, options).format(date) .

Note: Most of the time, the formatting returned by toLocaleString() is consistent. However, the output may vary with time, language, and implementation — output variations are by design and allowed by the specification. You should not compare the results of toLocaleString() to static values.

Examples

Using toLocaleString()

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0)); // toLocaleString() without arguments depends on the // implementation, the default locale, and the default time zone console.log(date.toLocaleString()); // "12/11/2012, 7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles 

Checking for support for locales and options parameters

The locales and options parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, toLocaleString() always uses the system’s locale, which may not be what you want. Because any implementation that supports the locales and options parameters must support the Intl API, you can check the existence of the latter for support:

function toLocaleStringSupportsLocales()  return ( typeof Intl === "object" && !!Intl && typeof Intl.DateTimeFormat === "function" ); > 

Using locales

This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // Formats below assume the local time zone of the locale; // America/Los_Angeles for the US // US English uses month-day-year order and 12-hour time with AM/PM console.log(date.toLocaleString("en-US")); // "12/19/2012, 7:00:00 PM" // British English uses day-month-year order and 24-hour time without AM/PM console.log(date.toLocaleString("en-GB")); // "20/12/2012 03:00:00" // Korean uses year-month-day order and 12-hour time with AM/PM console.log(date.toLocaleString("ko-KR")); // "2012. 12. 20. 오후 12:00:00" // Arabic in most Arabic-speaking countries uses Eastern Arabic numerals console.log(date.toLocaleString("ar-EG")); // "٢٠‏/١٢‏/٢٠١٢ ٥:٠٠:٠٠ ص" // For Japanese, applications may want to use the Japanese calendar, // where 2012 was the year 24 of the Heisei era console.log(date.toLocaleString("ja-JP-u-ca-japanese")); // "24/12/20 12:00:00" // When requesting a language that may not be supported, such as // Balinese, include a fallback language (in this case, Indonesian) console.log(date.toLocaleString(["ban", "id"])); // "20/12/2012 11.00.00" 

Using options

The results provided by toLocaleString() can be customized using the options argument:

const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // Request a weekday along with a long date const options =  weekday: "long", year: "numeric", month: "long", day: "numeric", >; console.log(date.toLocaleString("de-DE", options)); // "Donnerstag, 20. Dezember 2012" // An application may want to use UTC and make that visible options.timeZone = "UTC"; options.timeZoneName = "short"; console.log(date.toLocaleString("en-US", options)); // "Thursday, December 20, 2012, GMT" // Sometimes even the US needs 24-hour time console.log(date.toLocaleString("en-US",  hour12: false >)); // "12/19/2012, 19:00:00" 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Источник

Локализация даты, времени и чисел в JS при помощи .toLocaleString

Метод .toLocaleString — один из тех методов JavaScript, на которые редко обращают внимание. Я наткнулся на него, блуждая по сайту MDN, и с тех пор использую практически в каждом своем проекте.

В этой короткой статье я расскажу вам о .toLocaleString и о том, чем он может быть вам полезен.

.toLocaleString предназначен для форматирования даты и времени

.toLocaleString — это метод объекта Date. Он используется для перевода даты и числа в формат, специфический для определенного региона.

new Date().toLocaleString() // => 24/4/2022, 10:40:00 am

По умолчанию используются настройки локализации браузера, но вы можете указать нужную локализацию при помощи параметра locale .

console.log(new Date().toLocaleString('en-US')) // => 4/24/2022, 10:40:00 AM console.log(new Date().toLocaleString('en-GB')) // => 24/04/2022, 10:40:00 console.log(new Date().toLocaleString('ko-KR')) // => 2022. 4. 24. 오전 10:40:49

Вывод можно кастомизировать, указав формат даты.

console.log(new Date().toLocaleString('en-US', < year: 'numeric', weekday: 'long', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false, >)) // => Sunday, April 24, 2022 at 10:40:00 console.log(new Date().toLocaleString('en-US', < dateStyle: 'full', >)) // => Sunday, April 24, 2022 console.log(new Date().toLocaleString('en-US', < dateStyle: 'full', timeStyle: 'full', >)) // => Sunday, April 24, 2022 at 10:40:00 AM India Standard Time console.log(new Date().toLocaleString('en-US', < calendar: 'indian', >)) // => 2/4/1944 Saka, 10:40:00 AM // I don't know what that means either console.log(new Date().toLocaleString('en-US', < dayPeriod: 'long', >)) // => in the morning console.log(new Date().toLocaleString('en-US', < era: 'long', dayPeriod: 'long', weekday: 'long', month: 'long', year: 'numeric', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', fractionalSecondDigits: 3, timeZoneName: 'long', >)) // => Sunday, April 24, 2022 Anno Domini at 10:00:00.124 in the morning India Standard Time

Это полностью избавляет от необходимости использовать библиотеки для форматирования дат типа Moment.js!

От редакции Techrocks: возможно, вас также заинтересует статья «15 библиотек JavaScript, о которых стоит знать».

А еще с помощью этого метода можно форматировать числа!

.toLocaleString — это также метод для работы с числами. С его помощью можно перевести число в привычный для определенной географической местности формат.

console.log(10000000..toLocaleString()) // => 10,000,000

Локализация задается при помощи все того же параметра — locale .

console.log(10000000..toLocaleString('ar-EG')) // => ١٠٬٠٠٠٬٠٠٠ // Another language I know

Также можно добавлять опции:

// currency 10000..toLocaleString('en-US', ) // => $10,000.00 10000..toLocaleString('en-US', ) // => 10,000.00 US dollars (-11.29).toLocaleString('en-US', ) // => ($11.29) (-11.29).toLocaleString('en-US', ) // => -$11.29 // scientific 10000..toLocaleString('en-US', ) // => 1E4 10000..toLocaleString('en-US', ) // => 10K 1234..toLocaleString('en-US', ) // => 1.2K 1234..toLocaleString('en-US', ) // => 1.234E3 1234..toLocaleString('en-US', ) // => +1.234E3 0.55.toLocaleString('en-US', ) // => 55% 1234..toLocaleString('en-US', ) // => 1,234 L 1234..toLocaleString('en-US', ) // => 1,234L

Опять же, это избавляет от необходимости использовать кучи библиотек для форматирования чисел!

Для меня знакомство с методом .toLocaleString стало одним из самых неожиданных открытий в JavaScript.

Источник

Оцените статью