Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Date object in JavaScript

Posted in Javascript, javascript interview questions

date-in-javascript

Date() is an object in JavaScript. Date methods are used to find current day, current year also it is used to set value of year, month, date.

Example:

<p id="dateText"></p>

<script>
var date=new Date();
document.getElementById("dateText").innerHTML = date;
</script>

Above example will display current date and time in below format.
Sat Nov 28 2015 06:23:43 GMT-0800 (Pacific Standard Time

Example:

<p id="dateText"></p>

<script>
var date=new Date();
document.getElementById("dateText").innerHTML = date.toDateString();
</script>

toDateString() is used to display date in short format without time.
Sat Nov 28 2015

Methods:

getDate():
Display date as number.

getDay():
Display weekday as number.

getFullYear():
Display Full year in YYYY format.

getMonth():
Display month as number. JavaScript counts month from 0-11. Refer below example

Example:

<p id="dateText"></p>

<script>
var date=new Date();
document.getElementById("dateText").innerHTML = date.getMonth();
</script>

If current month is November then value of dateText will be 11. If you want to display day as text the create an array of day’s and accordingly display day values as string.

Example:

        var d=new Date();
	var weekday=new Array(7);
	weekday[0]="Monday";
	weekday[1]="Tuesday";
	weekday[2]="Wednesday";
	weekday[3]="Thursday";
	weekday[4]="Friday";
	weekday[5]="Saturday";
	weekday[6]="Sunday";
        var n = weekday.indexOf[d.getDay()];

Above code returns current day as string.