|
|
10 ways to format time and date using JavaScriptJavaScript has an inbuilt support for dates and times with its Date object. The methods of the Date object return various values associated with date and time. To start working with dates and time, we first initialize a variable and assign it a value with the new operator and the Date() constructor. The main function of the new operator with Date() constructor is to create a new date object that is stored in the variable. Here is the code: var d = new Date(); Thus, variable d contains a new date object. We can now call the various methods of this date object. Format #1: date-month-yearThe three methods that we would be using are:
<SCRIPT LANGUAGE="JAVASCRIPT"> <!-- var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth(); var curr_year = d.getFullYear(); document.write(curr_date + "-" + curr_month + "-" + curr_year); //--> </SCRIPT> This prints: In the code above, we have a different variable for the day, month and year. These variables all contain numeric quantities. (You can check this using typeof()). Hence, you can perform any kind of numerical operations on these variables. The eagle-eyed would have noticed that the month value returned by getMonth() is one less than the current month. This is because months start at 0 value, thus, January is represented by 0, February as 1, March as 2 ... <SCRIPT LANGUAGE="JAVASCRIPT"> <!-- var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth(); curr_month++; var curr_year = d.getFullYear(); document.write(curr_date + "-" + curr_month + "-" + curr_year); //--> </SCRIPT> Format #2: month/day/yearThis is very similar to the above: <SCRIPT LANGUAGE="JAVASCRIPT"> <!-- var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth(); curr_month++; var curr_year = d.getFullYear(); document.write(curr_month + "/" + curr_date + "/" + curr_year); //--> </SCRIPT>
Page contents: Formatting time and date using JavaScript - adding current dates to web pages - Javascript date object
Page URL: http://www.webdevelopersnotes.com/tips/html/ 27.php3
|
|