Cover image
Back-end
23 minute read

The Definitive Guide to DateTime Manipulation

Time and date manipulation is notoriously difficult. Developers encountering time zone rules, leap seconds, differences in locale-specific formatting are wise to resort to popular time and date manipulation libraries. But without thinking about how exactly they work, it's still easy to create all sorts of obscure bugs.

As a software developer, you can’t run away from date manipulation. Almost every app a developer builds will have some component where date/time needs to be obtained from the user, stored in a database, and displayed back to the user.

Ask any programmer about their experience handling dates and time zones and they will probably share some war stories. Handling date and time fields is certainly not rocket science but can often be tedious and error-prone.

There are hundreds of articles on the topic out there, however, most are either too academic, focusing on nitty-gritty details, or they are too patchy, providing short snippets of code without much explanation accompanying them. This in-depth guide to DateTime manipulation should help you understand the programming concepts and best practices relevant to time and date without having to browse through a sea of information on this topic.

In this article, I’m going to help you think clearly about date and time fields and suggest some best practices that can help you avoid date/time hell. Here we will explore some of the key concepts that are necessary for manipulating date and time values correctly, formats that are convenient for storing DateTime values and transferring them over APIs, and more.

For starters, the right answer for production code is almost always to use a proper library rather than rolling your own. The potential difficulties with DateTime calculation discussed in this article are only the tip of the iceberg, but they’re still helpful to know about, with or without a library.

DateTime Libraries Help If You Understand Them Correctly

Date libraries help in many ways to make your life easier. They greatly simplify date parsing, date arithmetic and logical operations, and date formatting. You can find a reliable date library for both the front end and the back end to do most of the heavy lifting for you.

However, we often use date libraries without thinking about how date/time actually works. Date/time is a complex concept. The bugs that come up due to its incorrect understanding can be extremely difficult to understand and fix, even with the help of date libraries. As a programmer, you need to understand the basics and be able to appreciate the problems that date libraries solve to make the most out of them.

Also, date/time libraries can only take you so far. All date libraries work by giving you access to convenient data structures to represent a DateTime. If you are sending and receiving data through a REST API, you will eventually need to convert the date to a string and vice versa because JSON doesn’t have a native data structure to represent DateTime. The concepts I have outlined here will help you to avoid some of the common issues that might come up when doing these date-to-string and string-to-date transformations.

Note: Even though I have used JavaScript as the programming language discussed in this article, these are general concepts that apply, to a large extent, to virtually all programming languages and their date libraries. So even if you’ve never written a line of JavaScript before, feel free to continue reading as I hardly assume any prior knowledge of JavaScript in the article.

Standardizing the Time

A DateTime is a very specific point in time. Let’s think about this. As I scribble this article, the clock on my laptop shows July 21 1:29 PM. This is what we call “local time,” the time that I see on wall clocks around me and on my wrist watch.

Give or take a few minutes, if I ask my friend to meet me at a nearby cafe at 3:00 PM, I can expect to see her there at roughly that time. Similarly, there wouldn’t be any confusion if instead I said, for example, “let’s meet in one and a half hours.” We routinely talk about time this way with people living in the same city or time zone.

Let’s think of a different scenario: I want to tell a friend living in Uppsala, Sweden that I want to talk to him at 5 PM. I send him a message, “Hey Anton, let’s talk at 5 PM.” I immediately get the response, “Your time or my time?”

Anton tells me that he lives in the Central European time zone which is UTC+01:00. I live in UTC+05:45. This means that when it is 5 PM where I live, it is 5 PM - 05:45 = 11:15 AM UTC, which translates to 11:15 AM UTC + 01:00 = 12:15 PM in Uppsala, perfect for both of us.

Also, be aware of the difference between time zone (Central European Time) and time zone offset (UTC+05:45). Countries can decide to change their time zone offsets for Daylight Savings Time for political reasons as well. Almost every year there’s a change to the rules in at least one country, meaning any code with these rules baked in must be kept up-to-date—it’s worth considering what your codebase depends on for this for each tier of your app.

That’s another good reason we’ll recommend that only the front end deals with time zones in most cases. When it doesn’t, what happens when the rules your database engine uses don’t match those of your front or back end?

This problem of managing two different versions of the time, relative to the user and relative to a universally accepted standard, is difficult, even more so in the world of programming where precision is key and even one second can make a huge difference. The first step towards solving these issues is to store DateTime in UTC.

Standardizing the Format

Standardizing the time is wonderful because I only need to store the UTC time and as long as I know the time zone of the user, I can always convert to their time. Conversely, if I know a user’s local time and know their time zone, I can convert that to UTC.

But dates and times can be specified in many different formats. For the date, you could write “Jul 30th” or “30 July” or “7/30” (or 30/7, depending on where you live). For the time, you could write “9:30 PM” or “2130”.

Scientists all over the world came together to tackle this problem and decided on a format to describe time that programmers really like because it’s short and precise. We like to call it “ISO date format,” which is a simplified version of the ISO-8601 extended format and it looks like this:

An image showing a simplified version of the ISO-8601 extended format called the ISO date format.

For 00:00 or UTC, we use “Z” instead, which means Zulu time, another name for UTC.

Date Manipulation and Arithmetic in JavaScript

Before we start with best practices, we will learn about date manipulation using JavaScript to get a grasp of the syntax and general concepts. Although we use JavaScript, you can adapt this information to your favorite programming language easily.

We will use date arithmetic to solve common date-related problems that most developers come across.

My goal is to make you comfortable creating a date object from a string and extracting components out of one. This is something that a date library can help you with, but it’s always better to understand how it is done behind the scenes.

Once we’ve gotten our hands dirty with date/time, it is then easier to think about the problems we face, extract the best practices, and move ahead. If you want to skip to the best practices, feel free to do so, but I would highly recommend you to at least skim through the date-arithmetic section below.

The JavaScript Date Object

Programming languages contain useful constructs to make our lives easier. The JavaScript Date object is one such thing. It offers convenient methods to get the current date and time, store a date in a variable, perform date arithmetic, and format the date based on the user’s locale.

Due to differences between browser implementations and incorrect handling of Daylight Savings Time (DST), depending on the Date object for mission-critical applications is not recommended and you should probably be using a DateTime library like Luxon, date-fns, or dayjs. (Whatever you use, avoid the once-popular Moment.js—often simply called moment, as it appears in code—since it’s now deprecated.)

But for educational purposes, we will use the methods that the Date() object provides to learn how JavaScript handles DateTime.

Getting Current Date

const currentDate = new Date();

If you don’t pass anything to the Date constructor, the date object returned contains the current date and time.

You can then format it to extract only the date part as follows:

const currentDate = new Date();

const currentDayOfMonth = currentDate.getDate();
const currentMonth = currentDate.getMonth(); // Be careful! January is 0, not 1
const currentYear = currentDate.getFullYear();

const dateString = currentDayOfMonth + "-" + (currentMonth + 1) + "-" + currentYear;
// "27-11-2020"

Note: The “January is 0” pitfall is common but not universal. It’s worth double-checking the documentation of any language (or configuration format: e.g., cron is notably 1-based) before you start using it.

Getting the Current Time Stamp

If you instead want to get the current time stamp, you can create a new Date object and use the getTime() method.

const currentDate = new Date();
const timestamp = currentDate.getTime();

In JavaScript, a time stamp is the number of milliseconds that have passed since January 1, 1970.

If you don’t intend to support <IE8, you can use Date.now() to directly get the time stamp without having to create a new Date object.

Parsing a Date

Converting a string to a JavaScript date object is done in different ways.

The Date object’s constructor accepts a wide variety of date formats:

const date1 = new Date("Wed, 27 July 2016 13:30:00");
const date2 = new Date("Wed, 27 July 2016 07:45:00 UTC");
const date3 = new Date("27 July 2016 13:30:00 UTC+05:45");

Note that you do not need to include the day of week because JS can determine the day of the week for any date.

You can also pass in the year, month, day, hours, minutes, and seconds as separate arguments:

const date = new Date(2016, 6, 27, 13, 30, 0);

Of course, you can always use ISO date format:

const date = new Date("2016-07-27T07:45:00Z");

However, you can run into trouble when you do not provide the time zone explicitly!

const date1 = new Date("25 July 2016");
const date2 = new Date("July 25, 2016");

Either of these will give you 25 July 2016 00:00:00 local time.

If you use the ISO format, even if you give only the date and not the time and time zone, it will automatically accept the time zone as UTC.

This means that:

new Date("25 July 2016").getTime() !== new Date("2016-07-25").getTime()
new Date("2016-07-25").getTime() === new Date("2016-07-25T00:00:00Z").getTime()

Formatting a Date

Fortunately, modern JavaScript has some convenient internationalization functions built into the standard Intl namespace that make date formatting a straightforward operation.

For this we’ll need two objects: a Date and an Intl.DateTimeFormat, initialized with our output preferences. Supposing we’d like to use the American (M/D/YYYY) format, this would look like:

const firstValentineOfTheDecade = new Date(2020, 1, 14); // 1 for February
const enUSFormatter = new Intl.DateTimeFormat('en-US');
console.log(enUSFormatter.format(firstValentineOfTheDecade));
// 2/14/2020

If instead we wanted the Dutch (D/M/YYYY) format, we would just pass a different culture code to the DateTimeFormat constructor:

const nlBEFormatter = new Intl.DateTimeFormat('nl-BE');
console.log(nlBEFormatter.format(firstValentineOfTheDecade));
// 14/2/2020

Or a longer form of the American format, with the month name spelled out:

const longEnUSFormatter = new Intl.DateTimeFormat('en-US', {
    year:  'numeric',
    month: 'long',
    day:   'numeric',
});
console.log(longEnUSFormatter.format(firstValentineOfTheDecade));
// February 14, 2020

Now, if we wanted a proper ordinal format on the day of the month—that is, “14th” instead of just “14”—this unfortunately needs a bit of a workaround, because day’s only valid values as of this writing are "numeric" or "2-digit". Borrowing Flavio Copes’ version of Mathias Bynens’ code to leverage another part of Intl for this, we can customize the day of the month output via formatToParts():

const pluralRules = new Intl.PluralRules('en-US', {
    type: 'ordinal'
})
const suffixes = {
    'one': 'st',
    'two': 'nd',
    'few': 'rd',
    'other': 'th'
}
const convertToOrdinal = (number) => `${number}${suffixes[pluralRules.select(number)]}`
// At this point:
// convertToOrdinal("1") === "1st"
// convertToOrdinal("2") === "2nd"
// etc.

const extractValueAndCustomizeDayOfMonth = (part) => {
    if (part.type === "day") {
        return convertToOrdinal(part.value);
    }
    return part.value;
};
console.log(
    longEnUSFormatter.formatToParts(firstValentineOfTheDecade)
    .map(extractValueAndCustomizeDayOfMonth)
    .join("")
);
// February 14th, 2020

Unfortunately, formatToParts isn’t supported by Internet Explorer (IE) at all as of this writing, but all other desktop, mobile, and back-end (i.e. Node.js) technologies do have support. For those who need to support IE and absolutely need ordinals, the sidenote below (or better, a proper date library) provides an answer.

If you need to support older browsers like IE before version 11, date formatting in JavaScript is tougher because there were no standard date-formatting functions like strftime in Python or PHP.

In PHP for example, the function strftime("Today is %b %d %Y %X", mktime(5,10,0,12,30,99)) gives you Today is Dec 30 1999 05:10:00.

You can use a different combination of letters preceded by % to get the date in different formats. (Careful, not every language assigns the same meaning to each letter—particularly, 'M' and 'm' may be swapped for minutes and months.)

If you are sure of the format you want to use, it is best to extract individual bits using the JavaScript functions we covered above and create a string yourself.

var currentDate = new Date();
var date = currentDate.getDate();
var month = currentDate.getMonth(); 
var year = currentDate.getFullYear();

We can get the date in MM/DD/YYYY format as

var monthDateYear  = (month+1) + "/" + date + "/" + year;

The problem with this solution is that it can give an inconsistent length to the dates because some months and days of the month are single-digit and others double-digit. This can be problematic, for example, if you are displaying the date in a table column, because the dates don’t line up.

We can address this by using a “pad” function that adds a leading 0.

function pad(n) {
    return n<10 ? '0'+n : n;
}

Now, we get the correct date in MM/DD/YYYY format using:

var mmddyyyy = pad(month + 1) + "/" + pad(date) + "/" + year;

If we want DD-MM-YYYY instead, the process is similar:

var ddmmyyyy = pad(date) + "-" + pad(month + 1) + "-" + year;

Let’s up the ante and try to print the date in “Month Date, Year” format. We will need a mapping of month indexes to names:

var monthNames = [
    "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
];

var dateWithFullMonthName = monthNames[month] + " " + pad(date) + ", " + year;

Some people like to display the date as 1st January, 2013. No problem, all we need is a helper function ordinal that returns 1st for 1, 12th for 12, and 103rd for 103, etc., and the rest is simple:

var ordinalDate = ordinal(date) + " " + monthNames[month] + ", " + year;

It is easy to determine the day of week from the date object, so let’s add that in:

var daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];


ordinalDateWithDayOfWeek = daysOfWeek[currentDate.getDay()] + ", " + ordinalDate;

The bigger point here is, once you’ve got the numbers extracted from the date, the formatting is mostly related to strings.

Changing the Date Format

Once you know how to parse a date and format it, changing a date from one format to another is just a matter of combining the two.

For example, if you have a date in the format Jul 21, 2013 and wanted to change the format to 21-07-2013, it can be achieved like this:

const myDate = new Date("Jul 21, 2013");
const dayOfMonth = myDate.getDate();
const month = myDate.getMonth();
const year = myDate.getFullYear();

function pad(n) {
    return n<10 ? '0'+n : n
}

const ddmmyyyy = pad(dayOfMonth) + "-" + pad(month + 1) + "-" + year;
// "21-07-2013"

Using JavaScript Date Object’s Localization Functions

The date formatting methods we discussed above should work in most applications, but if you really want to localize the formatting of the date, I suggest you use the Date object’s toLocaleDateString() method:

const today = new Date().toLocaleDateString('en-GB', {  
    day:   'numeric',
    month: 'short',
    year:  'numeric',
});

…gives us something like 26 Jul 2016.

Changing the locale to ‘en-US’ gives “Jul 26, 2016” instead. Notice how the formatting changed, but the display options were still kept the same—a very useful feature. As shown in the previous section, the newer Intl.DateTimeFormat-based technique works very similarly to this, but lets you reuse a formatter object so that you only need to set options once.

With toLocaleDateString(), it is a good habit to always pass the formatting options, even if the output looks fine on your computer. This can protect the UI from breaking in unexpected locales with really long month names or looking awkward because of short ones.

If I wanted the full month “July” instead, all I do is change the month parameter in the options to “long”. JavaScript handles everything for me. For en-US, I now get July 26, 2016.

Note: If you want the browser to automatically use the user’s locale, you can pass “undefined” as the first parameter.

If you want to show the numeric version of the date and don’t want to fuss with MM/DD/YYYY vs. DD/MM/YYYY for different locales, I suggest the following simple solution:

const today = new Date().toLocaleDateString(undefined, {
    day:   'numeric',
    month: 'numeric',
    year:  'numeric',
});

On my computer, this outputs 7/26/2016. If you want to make sure that month and date have two digits, just change the options:

const today = new Date().toLocaleDateString(undefined, {
    day:   '2-digit',
    month: '2-digit',
    year:  'numeric',
});

This outputs 07/26/2016. Just what we wanted!

You can also use some other related functions to localize the way both time and date are displayed:

CodeOutputDescription
now.toLocaleTimeString()
"4:21:38 AM" Display localized version of only time
now.toLocaleTimeString(undefined, {
    hour:   '2-digit',
    minute: '2-digit',
    second: '2-digit',
});
"04:21:38 AM" Display localized time based on options provided
now.toLocaleString()
"7/22/2016, 4:21:38 AM" Display date and time for user's locale
now.toLocaleString(undefined, {
    day:    'numeric',
    month:  'numeric',
    year:   'numeric',
    hour:   '2-digit',
    minute: '2-digit',
});
"7/22/2016, 04:21 AM" Display localized date and time based on options provided

Calculating Relative Dates and Times

Here’s an example of adding 20 days to a JavaScript Date (i.e., figuring out the date 20 days after a known date):

const myDate = new Date("July 20, 2016 15:00:00");
const nextDayOfMonth = myDate.getDate() + 20;
myDate.setDate(nextDayOfMonth);
const newDate = myDate.toLocaleString();

The original date object now represents a date 20 days after July 20 and newDate contains a localized string representing that date. On my browser, newDate contains “8/9/2016, 3:00:00 PM”.

To calculate relative time stamps with a more precise difference than whole days, you can use Date.getTime() and Date.setTime() to work with integers representing the number of milliseconds since a certain epoch—namely, January 1, 1970. For example, if you want to know when it’s 17 hours after right now:

const msSinceEpoch = (new Date()).getTime();
const seventeenHoursLater = new Date(msSinceEpoch + 17 * 60 * 60 * 1000);

Comparing Dates

As with everything else related to date, comparing dates has its own gotchas.

First, we need to create date objects. Fortunately, <, >, <=, and >= all work. So comparing July 19, 2014 and July 18, 2014 is as easy as:

const date1 = new Date("July 19, 2014");
const date2 = new Date("July 28, 2014");

if(date1 > date2) {
    console.log("First date is more recent");
} else {
    console.log("Second date is more recent");
}

Checking for equality is trickier, since two date objects representing the same date are still two different date objects and will not be equal. Comparing date strings is a bad idea because, for example, “July 20, 2014” and “20 July 2014” represent the same date but have different string representations. The snippet below illustrates the first point:

const date1 = new Date("June 10, 2003");
const date2 = new Date(date1);

const equalOrNot = date1 == date2 ? "equal" : "not equal";
console.log(equalOrNot);

This will output not equal.

This particular case can be fixed by comparing the integer equivalents of the dates (their time stamps) as follows:

date1.getTime() == date2.getTime()

I’ve seen this example in lots of places, but I don’t like it because you don’t create a date object from another date object usually. So I feel that the example is important from an academic point of view only. Also, this requires both Date objects to be referring to the exact same second, whereas you might only want to know if they refer to the same day or hour or minute.

Let’s look at a more practical example. You’re trying to compare whether the birthday the user has entered is the same as the lucky date you are getting from an API.

const userEnteredString = "12/20/1989"; // MM/DD/YYYY format
const dateStringFromAPI = "1989-12-20T00:00:00Z";

const dateFromUserEnteredString = new Date(userEnteredString)
const dateFromAPIString = new Date(dateStringFromAPI);

if (dateFromUserEnteredString.getTime() == dateFromAPIString.getTime()) {
    transferOneMillionDollarsToUserAccount();
} else {
    doNothing();
}

Both represented the same date but unfortunately your user will not get the million dollars.

Here’s the problem: JavaScript always assumes the time zone to be the one that the browser provides it unless explicitly specified otherwise.

This means, for me, new Date ("12/20/1989") will create a date 1989-12-20T00:00:00+5:45 or 1989-12-19T18:15:00Z which is not the same as 1989-12-20T00:00:00Z in terms of time stamp.

It’s not possible to change just the time zone of an existing date object, so our target is now to create a new date object but with UTC instead of local time zone.

We will ignore the user’s time zone and use UTC while creating the date object. There are two ways to do it:

  1. Create an ISO formatted date string from the user input date and use it to create a Date object. Using a valid ISO date format to create a Date object while making the intent of UTC vs local very clear.
const userEnteredDate = "12/20/1989";
const parts = userEnteredDate.split("/");

const userEnteredDateISO = parts[2] + "-" + parts[0] + "-" + parts[1];

const userEnteredDateObj = new Date(userEnteredDateISO + "T00:00:00Z");
const dateFromAPI = new Date("1989-12-20T00:00:00Z");

const result = userEnteredDateObj.getTime() == dateFromAPI.getTime(); // true

This also works if you don’t specify the time since that will default to midnight (i.e., 00:00:00Z):

const userEnteredDate = new Date("1989-12-20");
const dateFromAPI = new Date("1989-12-20T00:00:00Z");
const result = userEnteredDate.getTime() == dateFromAPI.getTime(); // true

Remember: If the date constructor is passed a string in correct ISO date format of YYYY-MM-DD, it assumes UTC automatically.

  1. JavaScript provides a neat Date.UTC() function that you can use to get the UTC time stamp of a date. We extract the components from the date and pass them to the function.
const userEnteredDate = new Date("12/20/1989");
const userEnteredDateTimeStamp = Date.UTC(userEnteredDate.getFullYear(), userEnteredDate.getMonth(), userEnteredDate.getDate(), 0, 0, 0);

const dateFromAPI = new Date("1989-12-20T00:00:00Z");
const result = userEnteredDateTimeStamp == dateFromAPI.getTime(); // true
...

Finding the Difference Between Two Dates

A common scenario you will come across is to find the difference between two dates.

We discuss two use cases:

Finding the Number of Days Between Two Dates

Convert both dates to UTC time stamp, find the difference in milliseconds and find the equivalent days.

const dateFromAPI = "2016-02-10T00:00:00Z";

const now = new Date();
const datefromAPITimeStamp = (new Date(dateFromAPI)).getTime();
const nowTimeStamp = now.getTime();

const microSecondsDiff = Math.abs(datefromAPITimeStamp - nowTimeStamp);

// Math.round is used instead of Math.floor to account for certain DST cases
// Number of milliseconds per day =
//   24 hrs/day * 60 minutes/hour * 60 seconds/minute * 1000 ms/second
const daysDiff = Math.round(microSecondsDiff / (1000 * 60 * 60  * 24));

console.log(daysDiff);

Finding User’s Age from Their Date of Birth

const birthDateFromAPI = "12/10/1989";

Note: We have a non-standard format. Read the API doc to determine if this means 12 Oct or 10 Dec. Change to ISO format accordingly.

const parts = birthDateFromAPI.split("/");
const birthDateISO = parts[2] + "-" + parts[0] + "-" + parts[1];

const birthDate =  new Date(birthDateISO);
const today = new Date();

let age = today.getFullYear() - birthDate.getFullYear();

if(today.getMonth() < birthDate.getMonth()) {
    age--;
}

if(today.getMonth() == birthDate.getMonth() && today.getDate() < birthDate.getDate()) {
    age--;
}

I know there are more concise ways to write this code but I like to write it this way because of the sheer clarity of the logic.

Suggestions to Avoid Date Hell

Now that we are comfortable with date arithmetic, we are in a position to understand the best practices to follow and the reasons for following them.

Getting DateTime from User

If you are getting the date and time from the user, you are most probably looking for their local DateTime. We saw in the date arithmetic section that the Date constructor can accept the date in a number of different ways.

To remove any confusion, I always suggest creating a date using new Date(year, month, day, hours, minutes, seconds, milliseconds) format even if you already have the date in a valid parsable format. If all programmers in your team follow this simple rule, it will be extremely easy to maintain the code in the long run since it is as explicit as you can be with the Date constructor.

The cool part is that you can use the variations that allow you to omit any of the last four parameters if they are zero; i.e., new Date(2012, 10, 12) is the same as new Date(2012, 10, 12, 0, 0, 0, 0) because the unspecified parameters default to zero.

For example, if you are using a date and time picker that gives you the date 2012-10-12 and time 12:30, you can extract the parts and create a new Date object as follows:

const dateFromPicker = "2012-10-12";
const timeFromPicker = "12:30";

const dateParts = dateFromPicker.split("-");
const timeParts = timeFromPicker.split(":");
const localDate = new Date(dateParts[0], dateParts[1]-1, dateParts[2], timeParts[0], timeParts[1]);

Try to avoid creating a date from a string unless it is in ISO date format. Use the Date(year, month, date, hours, minutes, seconds, microseconds) method instead.

Getting Only the Date

If you are getting only the date, a user’s birthdate for instance, it is best to convert the format to valid ISO date format to eliminate any time zone information that can cause the date to shift forward or backward when converted to UTC. For example:

const dateFromPicker = "12/20/2012";
const dateParts = dateFromPicker.split("/");
const ISODate = dateParts[2] + "-" + dateParts[0] + "-" + dateParts[1];
const birthDate = new Date(ISODate).toISOString();

In case you forgot, if you create a Date object with the input in valid ISO date format (YYYY-MM-DD), it will default to UTC instead of defaulting to the browser’s time zone.

Storing the Date

Always store the DateTime in UTC. Always send an ISO date string or a time stamp to the back end.

Generations of computer programmers have realized this simple truth after bitter experiences trying to show the correct local time to the user. Storing the local time in the back end is a bad idea, it’s better to let the browser handle the conversion to local time in the front end.

Also, it should be apparent that you should never send a DateTime string like “July 20, 1989 12:10 PM” to the back end. Even if you send the time zone as well, you are increasing the effort for other programmers to understand your intentions and parse and store the date correctly.

Use the toISOString() or toJSON() methods of the Date object to convert the local DateTime to UTC.

const dateFromUI = "12-13-2012";
const timeFromUI = "10:20";
const dateParts = dateFromUI.split("-");
const timeParts = timeFromUI.split(":");

const date = new Date(dateParts[2], dateParts[0]-1, dateParts[1], timeParts[0], timeParts[1]);

const dateISO = date.toISOString();

$.post("http://example.com/", {date: dateISO}, ...)

Displaying the Date and Time

  1. Get the time stamp or the ISO formatted date from a REST API.
  2. Create a Date object.
  3. Use the toLocaleString() or toLocaleDateString() and toLocaleTimeString() methods or a date library to display the local time.
const dateFromAPI = "2016-01-02T12:30:00Z";

const localDate = new Date(dateFromAPI);
const localDateString = localDate.toLocaleDateString(undefined, {  
    day:   'numeric',
    month: 'short',
    year:  'numeric',
});


const localTimeString = localDate.toLocaleTimeString(undefined, {
    hour:   '2-digit',
    minute: '2-digit',
    second: '2-digit',
});

When Should You Store the Local Time Too?

“Sometimes it’s important to know the time zone in which an event occurred, and converting to a single time zone irrevocably obliterates that information.

“If you’re doing a marketing promotion and want to know which customers placed orders around lunchtime, an order that appears to have been placed at noon GMT isn’t very helpful when it was actually placed over breakfast in New York.”

If you come across this kind of situation, it would be wiser to save the local time as well. As usual, we would like to create the date in ISO format, but we have to find the time zone offset first.

The Date object’s getTimeZoneOffset() function tells us the number of minutes that when added to a given local time gives the equivalent UTC time. I suggest converting it to (+-)hh:mm format because it makes it more obvious that it is a time zone offset.

const now = new Date();
const tz = now.gettime zoneOffset();

For my time zone +05:45, I get -345, this is not only the opposite sign, but a number like -345 might be completely perplexing to a back-end developer. So we convert this to +05:45.

const sign = tz > 0 ? "-" : "+";

const hours = pad(Math.floor(Math.abs(tz)/60));
const minutes = pad(Math.abs(tz)%60);

const tzOffset = sign + hours + ":" + minutes;

Now we get the rest of the values and create a valid ISO string that represents the local DateTime.

const localDateTime = now.getFullYear() +
                      "-" +
                      pad(now.getMonth()+1) +
                      "-" +
                      pad(now.getDate()) +
                      "T" +
                      pad(now.getHours()) +
                      ":" +
                      pad(now.getMinutes()) +
                      ":" +
                      pad(now.getSeconds());

If you want, you can wrap the UTC and local dates in an object.

const eventDate = {
    utc: now.toISOString(),
    local: localDateTime,
    tzOffset: tzOffset,
}

Now, in the back end, if you wanted to find out if the event occurred before noon local time, you can parse the date and simply use the getHours() function.

const localDateString = eventDate.local;
const localDate = new Date(localDateString);

if(localDate.getHours() < 12) {
    console.log("Event happened before noon local time");
}

We didn’t use the tzOffset here, but we still store it because we might need it in the future for debugging purposes. You could actually just send the time zone offset and UTC time only. But I like to store the local time too because you will eventually have to store the date in a database and having the local time stored separately allows you to directly query based on a field rather than having to perform calculations to get the local date.

Sometimes, even with the local time zone stored, you’ll want to display dates in a particular time zone. For example, times for events might make more sense in the current user’s time zone if they’re virtual, or in the time zone where they will physically take place, if they’re not. In any case, it’s worth looking beforehand at established solutions for formatting with explicit time zone names.

Server and Database Configuration

Always configure your servers and databases to use UTC time zone. (Note that UTC and GMT are not the same thing—GMT, for example, might imply a switch to BST during the summer, whereas UTC never will.)

We have already seen how much of a pain time zone conversions can be, especially when they are unintended. Always sending UTC DateTime and configuring your servers to be in UTC time zone can make your life easier. Your back-end code will be much simpler and cleaner as it doesn’t have to do any time zone conversions. DateTime data coming in from servers across the world can be compared and sorted effortlessly.

Code in the back end should be able to assume the time zone of the server to be UTC (but should still have a check in place to be sure). A simple configuration check saves having to think about and code for conversions every time new DateTime code is written.

It’s Time for Better Date Handling

Date manipulation is a hard problem. The concepts behind the practical examples in this article apply beyond JavaScript, and are just the beginning when it comes to properly handling DateTime data and calculations. Plus, every helper library will come with its own set of nuances—which is even true of the eventual official standard support{target=”_blank”} for these types of operations.

The bottom line is: Use ISO on the back end, and leave the front end to format things properly for the user. Professional programmers will be aware of some of the nuances, and will (all the more decidedly) use well-supported DateTime libraries on both the back end and the front end. Built-in functions on the database side are another story, but hopefully this article gives enough background to make wiser decisions in that context, too.