Is there any engineering reason why is it like that? I was wondering in the case of a RDBMS that it had something to do with performance, since a "YEAR" is more specific than a "MONTH", for instance: you only have one year 2000, but every year have "January", which would make it easier/faster to filter/sort something by year first, and that's why the year comes first.

But I don't know if that really makes sense... Is there any reason at all?

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

  • 14
    @IMil We may not like it, but quite often they are stored as strings. – Honza Brabec Sep 25 at 7:00
  • 14
    @candied_orange That would be strange, especially in the case of dates. – glglgl Sep 25 at 7:40
  • 39
    xkcd.com/1179 – Helio Sep 25 at 13:19
  • 19
    As a side note, this format is not that alien. For example, in Hungarian language (and probably some others too) YYYY. MM. DD. is the default written date format, and has been a long time before computers. – Neinstein Sep 25 at 20:50
  • 29
    In programming, the default date format is "YYYYMMDD"? It would be nice if that were true, but that's definitely not the case everywhere. RFC 822 and RFC 850, as well as ANSI C's asctime, are still widely used in a lot of places. It's nice that RFC 3339 and ISO 8601 are gradually displacing the older formats, and they're certainly what should be used going forward. More generally, I would say the ISO 8601 basic form (plain YYYYMMDD without separator characters) is actually less common than some other forms, like YYYY-MM-DD. – Daniel Pryden Sep 26 at 19:08

14 Answers 14

This way, the dates can easily be sorted as strings using the default sorting rules (i.e. lexicographical sorting).

This is also why both month and day are specified using two digits (adding a leading zero if needed).

The same sort logic works for ISO 8601 date format, when the date and time are represented like this: 2015-03-27T15:26:40Z.

However, YYYYMMDD has an added benefit of making it possible to easily (no substrings or character replacements involved) parse the string as an integer, and still use default ordering on integers.

  • 89
    @lucaswxp: If you write a special-case comparison for strings following a specific schema, you can of course make it as baroque as you want. The thing here is that the schema is designed such that lexical order (as well as lexical number-aware order) is also logical order, so no need for customizing. – Deduplicator Sep 25 at 0:48
  • 19
    @lucaswxp Your date string might not be in memory. Practical example: You have a csv file already sorted by ISO date and millions+ of rows per year. And you want to return only the rows between certain dates. You can read the file line by line (row by row) until you reach your first date, then load rows into memory until you reach your last date. You can skip the rest of the file. But if you save the date as some other format, or sorted by year only, you would have to read trough the entire year worth of records before closing the file. – Tom A. Vibeto Sep 25 at 5:00
  • 48
    Note that the dashes are optional in ISO 8601, so YYYYMMDD is ISO 8601. – Martin Ba Sep 25 at 11:14
  • 32
    @Benoit A proposal has already been made to solve the Y10K problem. If we're still using the same era then, we'll go to AYYYYYMMDD until Y100K, which will be BYYYYYYMMDD, CYYYYYYYMMDD, DYYYYYYYYMMDD, EYYYYYYYYYMMDD. This leading alpha prefix assures correct sort order (provided that "A0YYYY..." etc. are invalid representations if any YYYY... dates are still used). At some point when the number of year digits are divisible by three, we'll start adding three digits each time we change alpha prefix, in order to assure we don't run out of letters before the heat death of the universe. – Monty Harder Sep 25 at 15:00
  • 33
    It's important to note that with this format, sorting isn't just "easier." The lexical (character based) sort becomes equivalent to the temporal sort, which means you can sort temporally without parsing. – jpmc26 Sep 25 at 15:39

Not mentioned yet, but you quickly gloss over the order inside YYYY. That's already millennia, centuries, decades, years. That is to say, YYYY is already ordered from longest period to shortest period. The same goes for MM and DD, that's just how the number system works.

So to keep the order between fields consistent with the order within fields, the only option is YYYYMMDD.

As zahbaz and Arseni Mourzenko noted, the YYYYMMDD formats sorts easily. That is not a lucky coincidence, that's a direct consequence of putting the fields for the longest duration first (and keeping the length fixed; we are introducing a Y10K problem here.)

  • 33
    While you may be joking, this code may seriously come to haunt us in 8000 years. Code lives longer than anyone expects… 😓 – deceze Sep 25 at 15:42
  • 15
    @deceze ISO8601 already has provisions for a 5 digit year, but it would be interesting to see which DateTime implementations currently allow for it. – Zac Faragher Sep 26 at 2:16
  • 4
    @ZacFaragher, I'm sure we'll have plenty of time to implement that later, no need to rush, right...? – ilkkachu Sep 26 at 17:46
  • 49
    @deceze Why did you unfreeze me--have you figured out how to cure cancer? No, it is the year 9999 and you know COBOL. – user3067860 Sep 28 at 18:54
  • 6
    You may wish to fix your typo. The word millennia, the plural of millennium, is obligatorily spelled with a double-N to match the double-N in annual from Latin annus for year. When you misspell it with just a single-N, it now unhappily matches the single-N of anal from Latin anus with the same meaning as its loanword into English sports. In short, you always need to spell it in a way that means you’re talking about thousands of years, not thousands of butt-holes. :) – tchrist Sep 29 at 16:28

Is there any reason at all?

Yes. Those pieces of software will be using ISO 8601.

ISO 8601 has a number of advantages over other date formats:

  • It's a standard with a spec document :)
  • It's unambiguous. mm/dd/yyyy and dd/mm/yyyy can be confusing unless it's past the 13th day.
  • It lexicographically sorts into ascending time order, so no special date-sorting logic is required. This is especially useful in filenames, where lexicographical number sorting is often confusing (e.g. 1_file, 10_file, 2_file).
  • It mandates 4-digit year and zero padded month and year. This avoids the year 2000 problem and other ambiguities.

As for why ISO 8601 exists in the first place, it's because people were finding date-formats ambiguous and confusing when swapping data between countries/systems, and they needed something unambiguous.

For the rationale see the spec's introduction.

Although ISO Recommendations and Standards in this field have been available since 1971, different forms of numeric representation of dates and times have been in common use in different countries. Where such representations are interchanged across national boundaries misinterpretation of the significance of the numerals can occur, resulting in confusion and other consequential errors or losses. The purpose of this International Standard is to eliminate the risk of misinterpretation and to avoid the confusion and its consequences.

...

This International Standard retains the most commonly used expressions for date and time of the day and their representations from the earlier International Standards and provides unique representations for some new expressions used in practice. Its application in information interchange, especially between data processing systems and associated equipment will eliminate errors arising from misinterpretation and the costs these generate. The promotion of this International Standard will not only facilitate interchange across international boundaries, but will also improve the portability of software, and will ease problems of communication within an organization, as well as between organizations.

The standard defines “basic” variations as minimizing the use of delimiters. So, YYYYMMDD is the basic alternate to the extended format YYYY-MM-DD.

  • 4
    I didn't know that ISO 8601 also allowes YYYYMMDD besides YYYY-MM-DD. – keuleJ Sep 26 at 19:12
  • iso.org/iso-8601-date-and-time-format.html seems to indicate that the "Extended format" of YYYY-MM-DD is the only format for 8601? – Oskar Austegard Sep 27 at 19:08
  • 3
    @keuleJ Minimizing the use of delimiters such as YYYYMMDD rather than YYYY-MM-DD is called “basic” format variation in the ISO 8601 standard. – Basil Bourque Sep 27 at 21:55
  • Two more benefits of the ISO 8601: (a) Easy to parse by machine with no SPACE character and no localized text, and (b) Easy to intuit by humans across cultures with the year coming first being easy to recognize (if contemporary), and without assuming English language. – Basil Bourque Sep 27 at 22:06

It's because all the other ways to do it are ambiguous.

01/02/2003 what does that mean? January second 2003? Or in Europe: February 1st 2003? It gets even worse if you use two digits for the year, as 01/02/03.

That is why you use YYYYMMDD, it's the convention which enables us to communicate clearly about dates, 20030201 as a date is always clear. (and it makes it easier to sort)

(Now don't go storing that as the integer 20 million 30 thousand 2 hundred and 1. please ok? pretty please?)

  • 14
    "20030201 as a date is always clear": That is absolutely not the case. It is just as ambiguous as "01/02/2003" unless you know that YYYYMMDD (or is it YYYYDDMM or DDMMYYYY?...) is the format being used. You ALWAYS need to know the format of the date; there is no "convention" that makes things unambiguous. – skomisa Sep 27 at 17:20
  • 6
    @skomisa that is quite incorrect. ISO 8601 defined the international standard date format specifically for the reasons you stated. None of the other formats are valid date formats and have not been since 19880605 – K. Alan Bates Sep 27 at 20:25
  • 11
    @K.AlanBates Your date is ambiguous unless we assume that it should be parsed according to ISO 8601. – Goyo Sep 27 at 21:00
  • 16
    20030201 is the 20th of March 201AD, right? – David Richerby Sep 27 at 23:07
  • 10
    @Martijn, but language-specific. In Turkey, it is Şubat rather than February (Before you think your code works, always check Turkey). – NH. Sep 28 at 16:43

Let t1 and t2 be distinct integers that represent two times written in YYYYMMDD formatting. Then t1 < t2 implies that t2 occurred after t1.

You lose this ordering with DD and MM first formatting.

ISO is, IMO, the only sensible format.

  • 1
    Except you would never store this as an integer, at least I've never seen it nor considered it. – pipe Sep 25 at 10:54
  • 5
    @pipe: Believe me, some people would. We maintain a legacy system that stores YYYYMMDD as integers. The design probably originated in some old database system without an explicit date type and was kept for backwards compatibility. It's not pretty. Don't do it. – Heinzi Sep 25 at 11:19
  • 19
    @pipe it has been my experience in the software industry that whenever a reasonable person would want to say "But you would never do X" there is always at least one counter example – Joseph Rogers Sep 25 at 13:09
  • 5
    @pipe In data warehousing it's not uncommon to use a yyyymmdd integer as the primary/surrogate key for a table of dates. – soapygopher Sep 25 at 16:55
  • 4
    @pipe, well, the sequence number of a DNS zone is a 32-bit integer, which must be increased when the zone changes. While it could be just a plain number, a common idiom is to use numbers like 2018092601... Then there are some curious definitions of magic numbers in described in feature_test_macros(7), like having _POSIX_C_SOURCE > 200809L means that features from POSIX.1-2008 are supported... – ilkkachu Sep 26 at 17:56

One point not mentioned is that, in interactive inputs, this format allows to control the input.

The system cannot know if a month has 28, 29, 30 or 31 days without knowing the specific year and month. When the interactive input mandates that year and month come first it can check if the day (inserted last) is in the allowed range.

Granted, the question was largely about the date format, but it can be argued that the date format follows the formatting presented to the user.

YYYYMMDD orders dates the same way you orders numbers: most significant portion first. MMDDYYYY would be like writing "one hundred twenty three" as "twenty and one hundred three".

In our culture, we have a natural understanding of MMDDYYYY because, as humans, we have an awareness of time, and years progress slowly. We generally know what year it is. Seeing the year rarely matters, so we push it to the back. Months change over just fast enough to retain their importance. Other cultures handle this differnently. Much of the world prefer DDMMYYYY.

  • 61
    You may want to rephrase "our culture" because in my culture it's DDMMYYYY so it's not "our" culture just yours – slebetman Sep 25 at 5:38
  • 66
    Comprehensive map of all countries that use the MMDDYYYY date format img-9gag-fun.9cache.com/photo/a2mXmGd_700b.jpg – Peregrine Sep 25 at 7:02
  • 9
    Seems like an odd argument: "Months change over just fast enough to retain their importance" -> Why not then put the day first since that changes even faster? – Wim Deblauwe Sep 25 at 8:59
  • 7
    @JoelCoehoorn, it's easy to make that explicit ("In our U.S. culture"). "our"/"we" is often used to mean "the stackexchange community" here. – AnoE Sep 25 at 18:52
  • 14
    Exactly. Stackoverflow is international. That you are US based does not say, imply, or even make it more likely that others are as well. You cannot make any assumption about the locality of your readers here, they are all around the world. And most of your readers will be neither you, nor the OP, but other people who find your answer on Google. This very comment is written on a different continent than the one that you happen to live on. And while we have our own - ehm - interesting habits, we most certainly don't use MM/DD/YYYY here... – cmaster Sep 25 at 22:06

Sorting has been mentioned but by far the most useful reason for doing is to compare them as "strings", and yes a 26 character timestamp is ordered similarly.

I am aware such comparisons are essential for sorting, but it is generally useful for a 2 element sort.

I have worked on projects where this was not adopted, and yes, programmers tried (with mixed results) to compare the dates as strings.

Pretty formatting is for the client side or typesetting.

This format makes alphabetical order of the strings identical to chronological order of the dates. This is useful because many tools provide alphabetical ordering of e.g. files by name, but no way to parse arbitrarily-formatted dates from file names and sort by those.

It's about restrictiveness. Imagine YEAR, MONTH and DAY as parameters, in the format YYYYMMDD each parameter is more restrictive than the previous one.

So if you want to search something that happened in 1970 you can do it by searching a string starting by "1970*", but if you remeber which month was you can add the month like "197005*". This way every "parameter" of the date gives you more specific information.

It's the only way to go from less specific info ("1970*") to more specific info ("19700523").

  • 3
    Not really a great argument - it's just as common to search for things happening in specific months rather than specific years. – Cubic Sep 25 at 14:25
  • 1
    If 1970* and 197005* represent "glob" wildcard syntax, then you could search a bunch of MMDDYYYY dates by searching for the glob *1970 or 05*1970. Your answer might be implicitly assuming some extra constraint that you didn't explicitly mention, and could be improved by explaining your assumption. – Quuxplusone Sep 26 at 0:01
  • 3
    This is sort of a side-effect or another way of describing the sort-key order mentioned by other answers. But this explanation falls apart unless you restrict it to searching on prefixes. (Easier to index for, but by no means required). – Peter Cordes Sep 26 at 8:13
  • It also means you can select a sequence of dates with relatively simple regexp's... – Harper Oct 3 at 2:43

Why, in programming, the default date format is YYYYMMDD ...

It's a human readable format for input and output, it's not necessarily stored that way.

Over a third of all programming languages were developed in a country with English as the primary language and most of the modern ones adhere to a Standard of some description - the international Standard for dates is ISO 8601.

More info: (TMI?)

As time changes, usually forward, days increment first, then months, lastly years - it might be easier to understand if we had decimal dates (and decimal time) - as time passes the number gets bigger. It's simply easier for humans to look at the number and compare it to another date at a glance.

The computer doesn't care what structure you want to use and in most (but not all) computers binary logic is used - base e actually has the lowest radix economy but isn't the most efficient nor easiest for a complete sequence.

The actual input and output format for dates varies by country and is set by localization, while YYYYMMDD may seem to make the most sense and be what you are used to it isn't universal today, nor was it that way in the past for the longest time, yet even today Roman numerals are commonly used for dates.

Knowing the year upfront tells you the number of days in a year, the biggest variation in duration that a year can undergo. It tells you upfront the number of days in each month to follow (for error checking during entry), permitting input of the day first might have to back you up if the subsequent year did not agree with your input - possibly making accessible input more difficult. It also has importance with regards to the calendar format. See also the geek calendar, with its decimal stardates.

As far as the computer is concerned it's likely to use UNIX Epoch time, the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, where every day is treated as if it contains exactly 86400 seconds. See also the Julian day. The YYYYMMDD format is simply preferred by egocentric humans, the IAU regards a year as a Julian year of 365.25 days (31.5576 million seconds) unless otherwise specified.

  • 1
    Actually almost every human and piece of software I have ever met prefer some other format. – Goyo Sep 27 at 20:48
  • 1
    Pleased to meet you! I'm Dave, and I prefer YYYYMMDD – DaveBoltman Oct 5 at 10:38

Another use I've seen for this representation is that you can store dates as integers (i.e. in a database), using only 4 bytes per date. Using YYYYMMDD then means that integer comparisons (often a single machine instruction) have the same result as comparisons on the date represented. And it prints moderately human-readably. And none of this requires any code or special support at all, in any mainstream programming environment.

If those things are most of what you need to do with dates, and you need to do a lot of it, then this format has a lot of appeal.

By comparison, dates in common formats like DD/MM/YYYY take 10 bytes as strings of ASCII characters. YYYYMMDD strings reduce that to 8 and gain the "comparing the representations has the same result as comparing the dates" advantage, but even then string-based comparison is character-by-character rather than a single integer comparison.

  • 2
    It's trivial to pack a date into three bytes. The range 0000~9999 requires 14 bits, 01~12 requires 4 bits, and 01~31 requires 5 bits, for a sum of 23 bits. By using also the remaining bit in a three-byte quantity, you can represent dates over a period of 32,768 years maintaining a one-day resolution. This could be used, for example, to allow representing dates in the range year 8191 BC through 24576 AD. By packing the bits as, say, yyyyyyyyyyyyyyymmmmddddd, the decimal representation remains directly comparable (though not directly human readable, but who cares in database physical storage?). – Michael Kjörling Sep 27 at 18:57

Same reason the Moon is made of green cheese: it is not. In most cases the default format is some kind of localized string. Sometimes ISO format is used but usually with dashes for better readability. YYYYMMDD(or %Y%m%d in strftime parlance) is seldom the default. To be fair I am sure I have seen it but I cannot think of an example right now.

Unix date (GNU core utilities)

date

Output:

Wed Sep 26 22:20:57 CEST 2018

Python

import time
print(time.ctime())

output:

Wed Sep 26 22:27:20 2018

C

#include <stdio.h>
#include <time.h>

int main () {
   time_t curtime;

   time(&curtime);
   printf(ctime(&curtime));
   return(0);
}

Output:

Wed Sep 26 22:40:01 2018

C++

#include <ctime>
#include <iostream>

int main()
{
    std::time_t result = std::time(nullptr);
    std::cout << std::ctime(&result);
}

Output:

Wed Sep 26 22:51:22 2018

Javascript

current_date = new Date ( );
current_date;

Output:

Wed Sep 26 2018 23:15:22 GMT+0200 (CEST)

SQLite

SELECT date('now');

Output:

2018-09-26

LibreOffice Calc

enter image description here

Gnumeric

enter image description here

OnlyOffice

enter image description here

Python + numpy

import numpy as np
pd.datetime64('now')

Output:

numpy.datetime64('2018-09-26T21:31:55')

Python + pandas

import pandas as pd
pd.Timestamp('now', unit='s')

Output:

Timestamp('2018-09-26 21:47:01.277114153')

Software Engineering

enter image description here

apport.log

ERROR: apport (pid 9742) Fri Sep 28 17:39:44 2018: called for pid 1534, signal 6, core limit 0, dump mode 2

alternatives.log

update-alternatives 2018-05-08 15:14:24: run with --quiet --install /usr/bin/awk awk /usr/bin/mawk 5 --slave /usr/share/man/man1/awk.1.gz awk.1.gz /usr/share/man/man1/mawk.1.gz --slave /usr/bin/nawk nawk /usr/bin/mawk --slave /usr/share/man/man1/nawk.1.gz nawk.1.gz /usr/share/man/man1/mawk.1.gz

cups/access.log

localhost - - [28/Sep/2018:16:41:58 +0200] "POST / HTTP/1.1" 200 360 Create-Printer-Subscriptions successful-ok

syslog

Sep 28 16:41:46 pop-os rsyslogd:  [origin software="rsyslogd" swVersion="8.32.0" x-pid="946" x-info="http://www.rsyslog.com"] rsyslogd was HUPed
  • 10
    to add to your argument, how many of them are formatted that way because of user settings on the computer you ran the scrip on? – Topher Brink Sep 27 at 11:05
  • The first one is not really "bash", it is the date program (and it outputs Do 27. Sep 22:27:09 CEST 2018 here.) – Paŭlo Ebermann Sep 27 at 20:27
  • @PaŭloEbermann You are right, I hope it is better now. As I said many of these formats are localized so the actual format you see will depend on your localization options. – Goyo Sep 27 at 20:42
  • 3
    While the point of this Answer is true for end-user-oriented apps, not so for data exchange between systems, data serialization, message/data protocols, logging, tracing, debuggers, and so on. The ISO 8601 standard is rapidly becoming the norm for such uses aimed at system admins and programmers. Ditto for international or locale-agnostic scenarios. – Basil Bourque Sep 27 at 22:01
  • @BasilBourque Thanks, I added a random sample of the logs I found in my own system. I don't have examples of the other types handy. But I don't think that a trend towards defaulting to ISO 8601 in specific domains make its basic variant "the default in programming" in the face of the vast amount of software that defaults to other formats. – Goyo Sep 28 at 21:39

An additional benefit not mentioned so far is that desirable quantization (assigning a precise value as belonging to the same general range of values) is a relatively easy and fast single operation..

Suppose you're writing a report that summarises the events today, like the sum and number of sales. The sale date and time is stored as YYYYMMDDHHMISS, you simply need to keep the leftmost 8 characters (if it's a string) or integer divide (i.e. floor) by 1,000,000 to reduce your datetime to the day of the sale.

Similarly, if you wanted the month's sales, you keep only the leftmost 6 digits, or divide by 100,000,000

Sure, you could argue that any string manipulation is possible, a datetime for sales of "12-25-2018 12:34pm" could be substringed and manipulated multiple times to get the month and the year. In numeric form 122520181234 could be divided and modded, and multiplied, and divided some more, and eventually also produce a month and a year.. ..but the code would be really difficult to write, read, maintain and understand..

And even sophisticated database optimizers might not be able to make use of an index on a column for a where clause if the date form was MM/DD/YYYY but cut up and pieced back together. In comparison, storing a YYYYMMDD representation and wanting December 2018 leads to where clauses of the ilk dateasstring LIKE '201812%' or dateasint BETWEEN 20181200 and 20181299 - something an index can easily be used for

Thus, if there wasn't a dedicated datatype for dates and string/numerical representation was the only choice, using and storing times in some representation of longest-interval-on-the-left-to-shortest-interval-on-the-right has quite a few benefits for ease of understanding, manipulation, storage, retrieval and code maintenance

protected by gnat Sep 25 at 22:49

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.