Javascript date to char

How to convert a JavaScript date object to a string?

In this tutorial, we will learn to convert JavaScript date objects to a string. In JavaScript, we can invoke some methods on the string only. So, we need to convert the date to the string to use the date with such methods.

Here, we have three different approaches to converting the date object to a string.

Using the toString() Method

In this approach, we will use the toString() method of JavaScript to convert the date object to a string. The toString() method is useful to convert the variable of any data type such as number, objects, or array to string.

Syntax

Users can follow the syntax below to use the toString() method.

let date = new Date(); let datestr = date.toString();

Example

In the example below, we have created the date object using the constructor of the Date() class. We have used the toString() method to convert the date object to a string. Also, we have checked the type of converted string to clarify that object is converted to a string.

html> head> /head> body> h2>Converting date object to string in JavaScript./h2> h4>Convert date to string using i>toString()/i> method./h4> p id = "output1">/p> script> let output1 = document.getElementById("output1"); let date = new Date(); let datestr = date.toString(); output1.innerHTML += datestr + "
"
; output1.innerHTML += " Type of above date string is : " + typeof datestr; /script> /body> /html>

Using the toISOString() method

The toISOString() method is used to convert the date object into the ISO string format. It is a built-in method of the Date class of JavaScript.

Syntax

Users can follow the syntax below to use the toISOString() method.

let date = new Date(); let datestr = date.toISOString();

Example

In the example below, we have converted the date object to a string using the toISOString() method. Users can see in the output that the date format is also changed as we have converted the date object to an ISO string.

html> head> /head> body> h2>Converting date object to string in JavaScript./h2> h4>Convert date to string using i>date.toISOString()/i> method./h4> p id = "output1">/p> script> let output1 = document.getElementById("output1"); let date = new Date(); let datestr = date.toISOString(); output1.innerHTML += datestr + "
"
; output1.innerHTML += "Type of date string is : " + typeof datestr; /script> /body> /html>

Using the Moment.js format() Method

The Moment.js library includes the format() method to format the date object into the string format. In the parameter of the format() method, users can pass the required format for the date string.

Syntax

Users can follow the syntax below to use the .format() method of Moment.js.

date = moment().format('YY – MM - DD HH : mm : ss');

Parameters

All parameters of the moment.format() method is optional.

  • YY − It represents the year.
  • MM − It represents the Month.
  • DD − This parameter is for the day.
  • HH − It is for the hours.
  • mm − It is for the minutes.
  • ss − It represent the seconds.

Example

In the example below, we have used the Moment.js library of JavaScript. We have created two date objects; In the first object, we have formatted only the date string, and in the second object, we have formatted the date and time string.

html> head> script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment-with-locales.min.js" integrity="sha512-vFABRuf5oGUaztndx4KoAEUVQnOvAIFs59y4tO0DILGWhQiFnFHiR+ZJfxLDyJlXgeut9Z07Svuvm+1Jv89w5g= token operator">="anonymous" referrerpolicy="no-referrer"> /script> /head> body> h2>Converting date object to string in JavaScript./h2> h4>Convert date to string using i>moment().format()/i> method./h4> p id = "output1">/p> script> let output1 = document.getElementById("output1"); let date = moment().format('YY-MM-DD'); output1.innerHTML += "formatted date string only : " + date + "
"
; date = moment().format('YY-MM-DD HH : mm : ss'); output1.innerHTML += "formatted date and time strings : " + date + "
"
; /script> /body> /html>

Users have learned three approaches to converting the date object to a string. The modern approach is the last one, using the format() method of Moment.js. It allows users to set delimiter in the date string. However, users can also use the toDateString() method to solve the problem.

Источник

How to convert a date to a string in JavaScript

There are multiple ways to format a date in JavaScript. You can either use the built-in methods like toUTCString() and toISOString() , or the Intl.DateTimeFormat object.

The Date object in JavaScript exposes several built-in methods that you can use to display the date in different formats. By default, the toString() method outputs the date in full text string format:

const date = new Date(2021, 8, 14, 7, 14); console.log(date.toString()); // OR console.log(date); // Tue Sep 14 2021 07:14:00 GMT+0500 (Pakistan Standard Time) 
console.log(date.toUTCString()); // Tue, 14 Sep 2021 02:14:00 GMT 
console.log(date.toISOString()); // 2021-09-14T02:14:00.000Z 

Similarly, you can use toDateString() and toTimeString() methods to display only date and time parts of the Date object, respectively:

console.log(date.toDateString()); // Tue Sep 14 2021 console.log(date.toTimeString()); // 07:14:00 GMT+0500 (Pakistan Standard Time) 

You are not limited to the above methods only. Off course, you can also use methods like getDate() , getMonth() , and getFullYear() to retrieve day, month, and full year from a date object in JavaScript:

const day = date.getDate(); const month = date.getMonth() + 1; const year = date.getFullYear(); const str = `$day>/$month>/$year>`; console.log(str); // 14/9/2021 

The Intl.DateTimeFormat object is available in all modern browsers and IE 11. It provides methods for language-sensitive date and time formatting in JavaScript. One such method is format() that formats a date according to the locale and formatting options of the Intl.DateTimeFormat object. Here is an example that formats the date using the default locale:

const date = new Date(2021, 8, 14, 7, 14); const str = Intl.DateTimeFormat().format(date); console.log(str); // 14/9/2021 

If you need more localized date and time format, just pass the desired locale to Intl.DateTimeFormat() as shown below:

console.log(new Intl.DateTimeFormat('de-DE').format(date)); // 14.9.2021 console.log(new Intl.DateTimeFormat('ko-KR').format(date)); // 2021. 9. 14. console.log(new Intl.DateTimeFormat('ar-EG').format(date)); // ١٤‏/٩‏/٢٠٢١ 

The date object can be further customized by passing an options object to the Intl.DateTimeFormat() constructor:

const options =  weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' >; console.log(new Intl.DateTimeFormat('de-DE', options).format(date)); // Dienstag, 14. September 2021 options.timeZone = 'CET'; options.timeZoneName = 'short'; console.log(new Intl.DateTimeFormat('it-IT', options).format(date)); // martedì 14 settembre 2021, GMT+2 options.fractionalSecondDigits = 3; console.log(new Intl.DateTimeFormat('ar-EG', options).format(date)); // الاثنين، ١٣ سبتمبر ٢٠٢١ ٠٠٠ غرينتش-٥ 

You might also like.

Источник

Date.prototype.toISOString()

The toISOString() method of Date instances returns a string representing this date in the date time string format, a simplified format based on ISO 8601, which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ , respectively). The timezone is always UTC, as denoted by the suffix Z .

Try it

Syntax

Return value

A string representing the given date in the date time string format according to universal time. It’s the same format as the one required to be recognized by Date.parse() .

Exceptions

Thrown if the date is invalid or if it corresponds to a year that cannot be represented in the date string format.

Examples

Using toISOString()

const d = new Date(0); console.log(d.toISOString()); // "1970-01-01T00:00:00.000Z" 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 1, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How to convert a date object to string with format hh:mm:ss in JavaScript?

We will learn to convert the date object to a string with the format hh:mm:ss in JavaScript. It is a rear case that developers don’t use the date and time while developing the application. So, it is also important to learn to manipulate the dates.

The default date object returns the date string. Maybe it can be weird as you don’t need to show everything from it. So, users can format the date string according to their requirements. Here, we will see different approaches to format the date string.

Format the date using toISOString() method

In this approach, we will use the toISOString() method of the date class. We can create the date object of the Date class and invoke the toISOString() method by taking the date as a reference. We use this method to convert a date object to a string with format hh:mm: ss. It converts using ISO standard i.e. –

Syntax

Users can follow the syntax below to use the toISOString() method with the date object.

let myDate = new Date(); let datestr =myDate.toISOString();

Example

In the example below, we have created the object of the date class and invoked the toISOString() method by taking the date object as a reference. It returns the string in the hh: mm: ss format. Also, it returns the ISO time, So users can’t compare it with the local time. Furthermore, we have created the custom date by passing it as a parameter of the Date() class and invoked the toISOString() method.

html> head> /head> body> h2>Converting JavaScript date to string with format hh : mm : ss./h2> h4>Using the i> toISOString()/i> method to convert the time in the hh : mm : ss format /h4> p id = "output1"> /p> script> let output1 = document.getElementById("output1"); let myDate = new Date(); output1.innerHTML += "current date is : " + myDate.toISOString() + "
"
; // creating the date object for particular date myDate = new Date(2002, 2, 21, 10, 23, 59); output1.innerHTML += "created custom date and formatted it : " + myDate.toISOString() + "
"
; /script> /body> /html>

Using the moment.format() Method

The Moment.JS library for the date and time in JavaScript contains various methods to manipulate the date and time. One of them is the .format() method, which is useful to format the date according to our requirements.

Syntax

Users can follow the syntax below to use the moment().format() method.

let date = moment(); let dateStr = date.format("YY-MM-DD HH:mm:ss");

Parameters

  • YY-MM-DD HH:mm:ss − It represents the format of the string. Here, YY represents the year, MM represent month, and same way DD, HH, mm, ss represents the date, hour, minutes, and seconds respectively.

Example

In the example below, we have created the new date object using the moment() method. After that, we used the .format() method to format the date and time string in hh: mm: ss format. Users can observe the results in the output.

html> head> script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment-with-locales.min.js" integrity="sha512-42PE0rd+wZ2hNXftlM78BSehIGzezNeQuzihiBCvUEB3CVxHvsShF86wBWwQORNxNINlBPuq7rG4WWhNiTVHFg= token operator">="anonymous" referrerpolicy="no-referrer"> /script> /head> body> h2> Converting JavaScript date to string with format hh : mm : ss . /h2> h4> Using the i> moment().format() /i> method to convert the time in the hh : mm : ss format /h4> p id = "output1"> /p> script> let output1 = document.getElementById("output1"); let date = moment(); let dateStr = date.format("YY-MM-DD HH:mm:ss"); output1.innerHTML += "Current date is : " + dateStr + "
"
; /script> /body> /html>

Users have learned the two different approaches to convert the date and time into the required string format. We have to use the Moment.JS library, which is the best approach as it doesn’t take too much effort and can be done with a single line of code.

Also, users can get the year, month, date, and time separately using various methods and format the string, but users need to invoke the methods to get a single part of the date.

Источник

Читайте также:  Html hidden form button
Оцените статью