Getting Started with the Date
Object
The basic Date
constructor takes no parameters, and is initialized to the current date, as shown below.
We can clearly see that the resulting date depends on your local time zone, as two different time zones are shown.
var today = new Date();
// Thu Feb 27 2013 15:15:25 GMT+1000 (EST)
// Thu Feb 27 2013 10:45:25 GMT+0530 (IST)
There are two primary ways of using the Date
object:
- Custom dates can be generated by providing the format or specific date as the parameter to the
Date
constructor.date1 = new Date ( "January 6, 2013" );
- Then we can work with the created dates using dozens of built in functions. The following code shows you how to extract each component of a date using available functions.
date1 = new Date ( "January 6, 2013" ); date = date1.getDate(); year = date1.getFullYear(); month = date1.getMonth();
Date
object, and sets the day of the month to the 20th.
date1 = new Date ();
date1.setDate(20);
Also you are allowed to use numbers which don’t fall into the above ranges, to generate future or past dates. Consider the following example which uses values beyond the specified ranges.
date1 = new Date ();
date1.setDate(-1);
date1.setMonth(-1);
Assume that current date is February 20th, 2013. The above code will change to the second to last date of the previous month in the previous year, which would be December 30th, 2012. Similarly, you can use values greater than 31 for date and 11 for month to generate future dates. Having learned how to use Date
object to generate dates using various methods, let’s see how we can format dates.
Date Formatting
There is no single common format for dates, and we need to show date strings in different formats according to different situations. Basically, it is a two way process where we have to convert the string into aDate
object first and then convert it back to a string in the format we prefer. The initial process consists of converting the string provided by user input into a Date
object. Let’s consider some of the common user input methods for dates.
In the past, we had plain text fields or three option fields to select the month, day, and year. Nowadays, user input elements has been improved dramatically, and date pickers have become the modern way of selecting dates. Apart from date pickers, JavaScript calendars are a widely used component which we have to consider in this initial process. Dates from these components are retrieved as strings. If the date string contains a common format, we can just create the Date
object by passing the input field value as shown below.
// Assume date is 2013-02-15
var current = $("start_date").value();
var date1=new Date(current);
If you are working with calendars, the date will be specified as a HTML5 data attribute instead of the value property. An example of this is shown below.
var current = $("start_date").attr("date-current");
var date1=new Date(current);
Most date pickers and calendars provides a wide range of predefined formats you can use. But, if the component does not provide a common format, or the date is specified as a code, then we have to construct the Date
object manually by using functions as shown below.
var month = {"JAN":"01","FEB":"02"};
var current = "2013-FEB-22";
var date_components = current.split("-");
var current_year = date_components[0];
var current_month= month[date_components[1].toString()];
var current_day = date_components[2];
current = current_year+"-"+current_month+"-"+current_day;
var date11=new Date(current);
document.write(date1);
Since we know the meaning of each component, its possible to split the date string, and construct a common format to parse the Date
object.
Now we have converted the date string provided by user into a JavaScript Date
object to handle the validations, comparisons, and whatever else is required by the application. Finally, we have to convert it back a string to save it or display it in the web browser. This conversion is much easier than the previous one since we can use functions to break the components. I think you should have a common conversion function to reuse across all the projects. Let’s develop a simple function to convert dates into various string formats.
var date=new Date();
var format = "YYYY-MMM-DD DDD";
document.write(dateConvert(date,format));
function dateConvert(dateobj,format){
var year = dateobj.getFullYear();
var month= ("0" + (dateobj.getMonth()+1)).slice(-2);
var date = ("0" + dateobj.getDate()).slice(-2);
var hours = ("0" + dateobj.getHours()).slice(-2);
var minutes = ("0" + dateobj.getMinutes()).slice(-2);
var seconds = ("0" + dateobj.getSeconds()).slice(-2);
var day = dateobj.getDay();
var months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var dates = ["SUN","MON","TUE","WED","THU","FRI","SAT"];
var converted_date = "";
switch(format){
case "YYYY-MM-DD":
converted_date = year + "-" + month + "-" + date;
break;
case "YYYY-MMM-DD DDD":
converted_date = year + "-" + months[parseInt(month)-1] + "-" + date + " " + dates[parseInt(day)];
break;
}
return converted_date;
}
Here, we have a function which takes a Date
object and desired format as parameters. Inside the function, all the date components are assigned into variables using functions. Then, we have a switch
statement to choose the format. This kind of reusable utility function can be very effective for developing applications. When you are asked to provide a new format, just add another entry to the switch
statement, and return the components according to the new format. The output of the code will be 2013-FEB-17 SUN
. Likewise, you can convert it into your own preferred formats for displaying.
Date Comparisons
Searching records between a given date range is one of the most common use of dates in web applications. First, we have to convert the date string provided by user into aDate
object before thinking about comparisons. Let’s compare two dates generated with different methods, as shown below. It’s wise to use the getTime()
method to compare dates. Assume these dates were both generated on February 18th, 2013.
var date1=new Date();
var date2=new Date("2013-02-18");
if(date1.getTime() == date2.getTime()){
console.log("Dates are equal");
}
Even though both objects contain the same date, they are not equal. date1
contains the current date and will include the current time. But, date2
will not contain the current time, and hence it will not match.
The solution is to set the time of both objects to a standard time format. I have seen a lot of developers set the time to 00:00:00 for the current date object, as shown below.
var date1=new Date();
date1.setHours(0,0,0,0);
var date2=new Date("2013-02-18");
So, date1
will be something like Mon Feb 18 2013 00:00:00 GMT+0530 (IST)
. But, it still doesn’t match since date2
will contain the time in your local time zone, which is GMT+5.30 for me. If you don’t want to consider the time, the best way is to set both dates into the same time, as shown below.
var date1=new Date();
date1.setHours(0,0,0,0);
var date2=new Date("2013-02-17");
date2.setHours(0,0,0,0);
We can use same technique for comparing date ranges as well. Make sure to set all the other components of both dates to the same value and only check for the components which vary across both dates.
Should We Use a Date Manipulation Library?
Throughout the article we discussed how theDate
object works, and necessary functions we can use to manipulate dates. Choosing a date manipulation library is something you have to decide based on your requirements. Simple date handling can be done easily without a library. But, if you want complex functionality, I suggest you to use a date manipulation library like Datejs, which provides the ability to implement complex features through nested function calling.
And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Jump Start JavaScript.
Comments on this article are closed. Have a question about TOPIC? Why not ask it on our forums?
Frequently Asked Questions (FAQs) about JavaScript Date and Time
How can I convert a JavaScript date to a specific timezone?
JavaScript’s Date object works with the user’s local timezone by default. However, you can convert a date to a specific timezone using the toLocaleString() method. This method accepts a locale and an options object as arguments. The options object can include a timezone property, which you can set to the desired timezone. Here’s an example:let date = new Date();
let options = { timeZone: 'Asia/Kolkata' };
let newDate = date.toLocaleString('en-US', options);
console.log(newDate);
In this example, the date is converted to the ‘Asia/Kolkata’ timezone.
How can I compare two dates in JavaScript?
Comparing two dates in JavaScript can be done by converting the dates to their time equivalents using the getTime() method. This method returns the number of milliseconds since the Unix Epoch (January 1, 1970 00:00:00 UTC). Here’s an example:let date1 = new Date('2022-01-01');
let date2 = new Date('2022-01-02');
if (date1.getTime() < date2.getTime()) {
console.log('date1 is earlier than date2');
} else if (date1.getTime() > date2.getTime()) {
console.log('date1 is later than date2');
} else {
console.log('date1 and date2 are the same');
}
In this example, the script will output ‘date1 is earlier than date2’.
How can I add or subtract days from a JavaScript date?
You can add or subtract days from a JavaScript date using the setDate() and getDate() methods. The setDate() method sets the day of the month for a specified date according to local time, and the getDate() method returns the day of the month for the specified date according to local time. Here’s an example:let date = new Date();
// Add 5 days to the current date
date.setDate(date.getDate() + 5);
// Subtract 7 days from the current date
date.setDate(date.getDate() - 7);
In this example, 5 days are added to the current date, and then 7 days are subtracted from the current date.
How can I format a JavaScript date in a specific format?
JavaScript’s Date object doesn’t have a built-in method for formatting dates in a specific format. However, you can create a custom function to format a date in the desired format. Here’s an example:function formatDate(date) {
let year = date.getFullYear();
let month = ('0' + (date.getMonth() + 1)).slice(-2);
let day = ('0' + date.getDate()).slice(-2);
return year + '-' + month + '-' + day;
}
let date = new Date();
console.log(formatDate(date)); // Outputs: yyyy-mm-dd
In this example, the formatDate() function formats a date in the ‘yyyy-mm-dd’ format.
How can I get the current timestamp in JavaScript?
You can get the current timestamp in JavaScript using the Date.now() method. This method returns the number of milliseconds elapsed since the Unix Epoch. Here’s an example:let timestamp = Date.now();
console.log(timestamp);
In this example, the current timestamp is logged to the console.
How can I parse a date string in JavaScript?
You can parse a date string in JavaScript using the Date.parse() method. This method parses a string representation of a date and returns the number of milliseconds since the Unix Epoch. Here’s an example:let timestamp = Date.parse('2022-01-01');
console.log(timestamp);
In this example, the timestamp for the date ‘2022-01-01’ is logged to the console.
How can I get the day of the week in JavaScript?
You can get the day of the week in JavaScript using the getDay() method. This method returns the day of the week for the specified date according to local time, where 0 represents Sunday. Here’s an example:let date = new Date();
let dayOfWeek = date.getDay();
console.log(dayOfWeek);
In this example, the day of the week for the current date is logged to the console.
How can I get the number of days in a month in JavaScript?
You can get the number of days in a month in JavaScript using the Date object. Here’s an example:function getDaysInMonth(year, month) {
return new Date(year, month, 0).getDate();
}
console.log(getDaysInMonth(2022, 1)); // Outputs: 31
In this example, the getDaysInMonth() function returns the number of days in the specified month.
How can I convert a timestamp to a date in JavaScript?
You can convert a timestamp to a date in JavaScript using the Date object. The Date object accepts a timestamp as an argument and returns a new Date object. Here’s an example:let timestamp = 1641235200000;
let date = new Date(timestamp);
console.log(date);
In this example, the timestamp is converted to a date and logged to the console.
How can I get the current date and time in JavaScript?
You can get the current date and time in JavaScript using the Date object. When the Date object is instantiated without any arguments, it represents the current date and time. Here’s an example:let date = new Date();
console.log(date);
In this example, the current date and time are logged to the console.
Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on Building Impressive Presentations with Impress.js. He is a regular contributor to 1stWebDesigner, Tuts+ network and SitePoint network. Make sure to follow him on Google+.