Step 1: Create an Object Date
Date object contains year, month, day, hour, minute, seconds and milliseconds. The below code will creates a new date object with the current date and time
1
| var today = new Date(); //date object |
Sat Sep 23 2017 11:35:59 GMT+0530 (India Standard Time)
Step 2: Getting Javascript Current Date from Date Object
Date object has different methods to parse the date from date object. You can get the Date, Month and Year from getDate() , getMonth() , getYear() methods.var today = new Date(); var current_date = today.getDate(); var current_month = today.getMonth()+1; //Month starts from 0 var current_year = today.getFullYear(); alert(current_date+ "/" +current_month+ "/" +current_year); |
getMonth() – you need to add +1 to display the correct month because javascript month starts from 0.Above code will give you the current date as below format (DD/MM/YYYY)
23/9/2017
Step 3: Getting Javascript Current Time from Time Methods
For getting current time, I have used prototype constructor for the date object. Date.prototype.getCurrentTime – getCurrentTime function will be inherited by all the instances of Date Object.Date.prototype.getCurrentTime = function (){ return (( this .getHours() < 10)? "0" : "" ) + (( this .getHours()>12)?( this .getHours()-12): this .getHours()) + ":" + (( this .getMinutes() < 10)? "0" : "" ) + this .getMinutes() + ":" + (( this .getSeconds() < 10)? "0" : "" ) + this .getSeconds() + (( this .getHours()>12)?( ' PM' ): ' AM' ); }; |
var current_time = today.getCurrentTime(); |
14:12:34 AM
Lets combine all the above codes and will give you the javascript current date and time using date object
Final Javascript Code to get Current Date & Time
Date.prototype.getCurrentTime = function (){ return (( this .getHours() < 10)? "0" : "" ) + (( this .getHours()>12)?( this .getHours()-12): this .getHours()) + ":" + (( this .getMinutes() < 10)? "0" : "" ) + this .getMinutes() + ":" + (( this .getSeconds() < 10)? "0" : "" ) + this .getSeconds() + (( this .getHours()>12)?( ' PM' ): ' AM' ); }; var today = new Date(); //date object var current_date = today.getDate(); var current_month = today.getMonth()+1; //Month starts from 0 var current_year = today.getFullYear(); var current_time = today.getCurrentTime(); alert(current_date+ "/" +current_month+ "/" +current_year+ ' - ' +current_time); |
Output,
23/9/2017 – 14:12:34 AM
0 comments:
Post a Comment