17

Is there any way to get system short date format in JavaScript?

For example whether system's short date is in American format eg. m/d/Y or in european eg. d/m/Y

Please note: This is not question about formatting date or calculating it based on geolocation, but about getting the format from the OS/system

WooDzu
  • 4,771
  • 6
  • 31
  • 61
  • Are you asking whether or not you can find out which one the user has in the bottom right of their screen? Or are you asking which one the user *should* have based on their location? – George Apr 25 '13 at 08:40
  • Hi F4r-20. Yes I meant the default system's time - the clock uses it too. – WooDzu Apr 25 '13 at 08:44
  • 1
    Good question. I don't think there's a way to tell directly, but perhaps you could work it out by formatting a known date with `.toLocaleDateString()` and then testing the resulting string to see if it ended up starting with the month? – nnnnnn Apr 25 '13 at 08:49
  • 1
    see if this thread helps http://stackoverflow.com/q/2388115/276263 – krishnakumarp Apr 25 '13 at 08:58
  • try this date.toLocaleDateString() – hayat Apr 25 '13 at 09:19
  • I think the answer is simple: No, you cannot access the systems date mechanisms from the browser without the use of proprietary plugins. – Bergi Apr 25 '13 at 09:32
  • possible duplicate of [How to detect the user's local date and time format](http://stackoverflow.com/questions/5548783/how-to-detect-the-users-local-date-and-time-format) – Oleg V. Volkov Apr 25 '13 at 15:13
  • 1
    Been there, cursed that. Ended up giving the user a short list of standard formats in a combobox and recording the choice in the user profile in my app's database. Browser support for this is super lame. – Peter Wone Aug 06 '13 at 13:05
  • I think you are talking about this right? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString – Joel Chu Oct 23 '20 at 13:44
  • Does this answer your question? [Get Locale Short Date Format using javascript](https://stackoverflow.com/questions/2388115/get-locale-short-date-format-using-javascript) – Jack Miller Sep 08 '21 at 05:50

8 Answers8

5

After a pinch of research I concluded that technically it's not possible to get regional settings -and by this, date format- but you can do several other things. Pick one of these options:
a) The already mentioned -and outdated- "toLocaleString()" function:

var myDate = new Date(1950, 01, 21, 22, 23, 24, 225);
var myDateFormat = myDate.toLocaleString();
alert (myDateFormat);

ISSUES:
1) You can't "myDateFormat.replace" to get the date mask as month is not stored as "01", "02", etc in the string but as text instead, based on locale (like "February" in English but it's "Φεβρουάριος" in Greek and who knows what in e.g. Klingon).
2) Different behavior on different browsers
3) Different behavior on different OS and browser versions...

b) Use the toISOString() function instead of toLocaleString(). You won't get the locale date mask but get a date from which you can tell where's which part of the date (ie where "month" or "day" is in that string). You can also work with getUTCDate(), getUTCMonth() and getUTCDay() functions. You still can't tell what date format the client uses, but can tell which Year/Month/Day/etc you work with when you grab a date; use the code above to test the functions I mentioned here to see what you can expect.

c) Read Inconsistent behavior of toLocaleString() in different browser article and use the (IMHO great) solution described there

Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
  • Hi Mark, thanks for your Answer. I share your point but this is still relaying on Browser – WooDzu Apr 25 '13 at 09:26
  • If you mean option 'c' yes, you are right, the problem is noted as browser issue but the solution is more generic. On the other hand, I would go with 'b' if I was you. If it's a must to know date format mask, there's another option: "myDateFormat.replace("1950", "yyyy");", etc - but for month, you need to find the string start-end and replace that range with "mm" - which makes your script a bit too complicated, possible even for your goal... –  Apr 25 '13 at 09:31
  • The only issue is that if for example my system clock, excell spreadsheet and whole bunch of other apps are using d/m/Y and my browser would detect 'en-US' for some reason (yes it does that) it will use the en-US format ie m/d/Y – WooDzu Apr 25 '13 at 10:15
  • 1
    I understand. But the issue with javascript workarounds is regional settings can be unique on every and all systems as user can customize displayed date/time format to whatever they want. E.g. my computer has en-US locale (I like setting this as I use EN OS with EN keyboard) but I set my date/time format to Hungarian ("yyyy.mm.dd, DDDD" and "HH:mm:ss") as I'm Hungarian. And this format is not the Hungarian standard. I just like it this way... This is why "no" is the answer to your question. It is impossible to write a script that works perfectly on all and every system to "extract" date format –  Apr 25 '13 at 10:52
  • On a side note an empty input type=time shows the format exactly as it's configured in the system but I haven't found a way of retrieving it from JavaScript – WooDzu Jun 14 '13 at 07:22
2

for my case i used a custom date that i know what number is day, what is month and what is year so it can possible with a simple replace statement.

let customDate = new Date(2222, 11, 18);
let strDate = customDate.toLocaleDateString();
let format = strDate
    .replace("12", "MM")
    .replace("18", "DD")
    .replace("2222", "yyyy");
Mahdi Aslami Khavari
  • 1,755
  • 15
  • 23
1

A very good but lengthy answer can here found here: https://stackoverflow.com/a/9893752/2484903

A shorter one here:

let customDate = new Date(2222, 3, 8);
let strDate = customDate.toLocaleDateString();
let format = strDate
    .replace("04", "MM")
    .replace("4", "M")
    .replace("08", "dd")
    .replace("8", "d")
    .replace("2222", "yyyy")
    .replace("22", "yy");
console.log(format);

We create a date object of a known date and then parse the outcome.

First we look for "04" (which corresponds to 3 from the date definition); that would be the two digit month format MM. If not found, it must be the single digit format M. Afterwards do the same for day and year.

Jack Miller
  • 6,843
  • 3
  • 48
  • 66
0

It is not possible. You can get culture from user browser and use some js libraries to convert to correct date format. http://code.google.com/p/datejs/

Reno
  • 1,291
  • 4
  • 17
  • 29
0

I made a function to determine the client date format. The function determine the date format separator, and also determine the 1st, 2nd and third part of the date format.

getDateFormat(){
    // initialize date value "31st January 2019"
    var my_date = new Date(2019,0,31);
    console.log(my_date.toLocaleDateString());
    // Initialize variables
    var separator="";
    var first="";
    var second="";
    var third="";
    var date_parts = [];

    // get separator : "-", "/" or " ", format based on toLocaleDateString function        
    if (my_date.toLocaleDateString().split("-").length==3){
        separator = " - ";
        date_parts = my_date.toLocaleDateString().split("-");
    } 
    if (my_date.toLocaleDateString().split("/").length == 3) {
        separator = " / ";
        date_parts = my_date.toLocaleDateString().split("/");
    } 
    if (my_date.toLocaleDateString().split(" ").length == 3) {
        separator = " ";
        date_parts = my_date.toLocaleDateString().split(" ");
    } 

    // get first part        
    if (date_parts[0]==2019){
        first ="yyyy";
    } else if (date_parts[0] == 31){
        first = "dd";
    } else{
        if (date_parts[0].length<=2){
            first ="mm";
        }
        else{
            first="mmm";
        }
    }

    // get second part        
    if (date_parts[1] == 2019) {
        second = "yyyy";
    } else if (date_parts[1] == 31) {
        second = "dd";
    } else {
        if (date_parts[1].length <= 2) {
            second = "mm";
        }
        else {
            second = "mmm";
        }
    }

    // get third part        
    if (date_parts[2] == 2019) {
        third = "yyyy";
    } else if (date_parts[2] == 31) {
        third = "dd";
    } else {
        if (date_parts[2].length <= 2) {
            third = "mm";
        }
        else {
            third = "mmm";
        }
    }

    // assembly
    var format = first + separator + second + separator + third;
    console.log(format);
    return format;
}
Hodeifa Baswel
  • 167
  • 1
  • 4
0

I've created a workaround to determine which format the user's browser is using. This is in C# but the logic is the same:

Here are the steps:

  1. First try to convert the user's browser date into American format (mm-dd-yyyy). Convert.ToDateTime is using the American date format.

  2. If that fails it means the user is using European format (dd-mm-yyyy). However, this will only cover the day 13 to 31 because this is not a valid month.

  3. If the conversion is successful, do another check to determine if the converted date is between the current UTC day + 1 day (to cover UTC+14) and current UTC day - 1 day (to cover UTC-12). https://www.timeanddate.com/time/current-number-time-zones.html

  4. If the converted date is out of the current date range, it means the user's browser is using European format (dd-mm-yyyy) and you can convert it to American format if you want.

             string localeDateString = "01/11/2020"; // e.g. input is using European format (dd-mm-yyyy)
             var localeDate = new DateTime();
    
             try
             {
                 localeDate = Convert.ToDateTime(localeDateString);
                 //var checkTheFormatOfDateInput = localeDate.ToLongDateString();
                 var currentDateTime = DateTime.UtcNow;
                 //var currentDateTime = Convert.ToDateTime("11/01/2020");
                 //var checkTheFormatOfCurrentDate = Convert.ToDateTime("11/01/2020").ToLongDateString();
                 var currentDateTimePositive = currentDateTime.AddDays(1);
                 var currentDateTimeNegative = currentDateTime.AddDays(-1);
    
                 var outOfCurrentDateRange = !(localeDate.Ticks > currentDateTimeNegative.Ticks && localeDate.Ticks < currentDateTimePositive.Ticks);
    
                 if (outOfCurrentDateRange)
                 {
                     localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                 }
             }
             catch
             {
                 localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
             }
    
             //var checkTheEndResultFormat = localeDate.ToLongDateString();
    

Below is the clean code wrapped in a method:

    private DateTime ConvertAmericanOrEuropeanDateFormatToAmericanDateFormat(string localeDateString)
    {
        var localeDate = new DateTime();

        try
        {
            localeDate = Convert.ToDateTime(localeDateString);
            var currentDateTime = DateTime.UtcNow;
            var currentDateTimePositive = currentDateTime.AddDays(1);
            var currentDateTimeNegative = currentDateTime.AddDays(-1);

            var outOfCurrentDateRange = !(localeDate.Ticks > currentDateTimeNegative.Ticks && localeDate.Ticks < currentDateTimePositive.Ticks);

            if (outOfCurrentDateRange)
            {
                localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
            }
        }
        catch
        {
            localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
        }

        return localeDate;
    }
Verosai
  • 1
  • 1
0

It should do the job...

function getSystemDateLocale(){
    let testDate = (new Date('2000-1-30')).toLocaleDateString()
    if (testDate.substring(0,2) == '30') return 'EU'
    else return 'US'
}
  • While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Luca Kiebel Jan 20 '22 at 11:58
-1

Use Date.CultureInfo.formatPatterns.shortDate

Ben
  • 1
  • Hi. Just chhecked. Where did you take CultureInfo from? The Date object in Firefox and Chrome doesn't have it – WooDzu Nov 11 '13 at 21:05