Moreover, if you want to get the date and time separately, you can use the toLocaleDateString() and toLocaleTimeString() methods. In your browser, the result will look like in the following format as shown below. Then, I used the JavaScript getElementById() method to print the output on the screen.Second, I used the toLocaleString() method.In the above JavaScript code, first I created a date object.print output on the screen using getElementById method document.getElementById( 'demo').innerHTML = datestring use toLocaleString() like this below var datestring = todayDate.toLocaleString() first store date object in a variable var todayDate = new Date() The following code example shows the syntax to use the toLocaleString() method to convert a date object to a string in JavaScript. Simply its output will look the same as the date and time of your system. Mean this method returns the date and time using the system’s locale-specific formatting. We can use JavaScript toLocaleString() method to convert the date object to a string based on the user’s locale. This method is very useful when we need just the date portion and want to exclude time. The output will look like this below, it shows the current date as a string. In the above code, I did a minor change in the second line of code, where I used todayDate.toDateString(). print output on the screen document.write(datestring) use toDateString() like this below var datestring = todayDate.toDateString() The following JavaScript code shows the syntax to use the toDateString() method. It outputs a string representing the date in the format “Day Mon DD YYYY”. It works the same way as we use the toString() method and the only difference is it returns the date portion excluding time. The toDateString() is another JavaScript built-in method that is used to convert string to date in JavaScript. However, the date format might be different depending on your browser. The output will look like this below, depending on your browser’s current date and time. However, you can also use console.log() to print the output in your browser’s console.
0 Comments
Leave a Reply. |