Setting Dates in JavaScript

Setting Dates in JavaScript
In a recent article we looked at the the JavaScript date object, in general. Here we look at all the methods for setting different parts of a date and time according to the local time. (Remember, local time is whatever time and timezone the computer the user is using is set to.) While none of these methods look very interesting on their own, in combination with other date methods, they allow you to do all sorts of date and calendar calculations.

Date is set prior to each example to Monday, December 20, 1999 8:30:15 PM using var egdate=new Date("December 20, 1999 20:30:15"). If you have JavaScript available in your browser, you can see a live example here.

setDate()
sets the date (day of month) in an existing date object
EXAMPLE: egdate.setDate(12) RESULT: Monday, December 20, 1999 8:30:15 PM
setMonth()
sets the month in an existing date object
EXAMPLE: egdate.setMonth(2) RESULT: Saturday, March 20, 1999 8:30:15 PM
setFullYear()
sets the year (4 digit form) in an existing date object
There is also an obsolete setYear() function, but it should be avoided whenever possible
EXAMPLE: egdate.setFullYear(2008) RESULT: Saturday, December 20, 2008 8:30:15 PM
setHours()
sets the hours portion of the time of day in an existing date object (uses a 24 hour clock)
EXAMPLE: egdate.setHours(14) RESULT: Monday, December 20, 1999 2:30:15 PM
setMinutes()
sets the minutes portion of the time of day in an existing date object
EXAMPLE: egdate.setMinutes(17) RESULT: Monday, December 20, 1999 8:17:15 PM
setSeconds()
sets the seconds portion of the time of day in an existing date object
EXAMPLE: egdate.setSeconds(24) RESULT: Monday, December 20, 1999 8:30:24 PM
setMilliseconds()
sets the milliseconds portion of the time of day in an existing date object
EXAMPLE: egdate.setMilliseconds(300) RESULT: Monday, December 20, 1999 8:30:15 PM
setTime()
sets the date and time of an existing Date object using seconds since (before for negative numbers) January 1, 1970
EXAMPLE: egdate.setTime(-999999999) RESULT: Monday, December 20, 1999 8:30:15 PM


This site needs an editor - click to learn more!


You Should Also Read:
Introduction To The JavaScript Date Object
Getting Dates and Parts of Dates
Introduction to UTC Dates

RSS
Related Articles
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Julie L Baumler. All rights reserved.
This content was written by Julie L Baumler. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.