ToLocaleDateString () short format

I want to have a short Date.toLocaleDateString () notation, but in local format. There are many solutions that hardcode the yyyy-mm-dd format, but I want it to depend on the system on which the page is hosted. This is my function so far:

    function getDate(dateTimeString)
    {
        var date    = getDateTime(dateTimeString);
        var options = { year: "numeric", month: "numeric", day: "numeric" };        
        return date.toLocaleDateString( date.getTimezoneOffset(), options );
    }

but that returns it like this: Wednesday, January 28, 2015, which I don't want. Any suggestions / ideas?

PS: this is not a browser, and there is a pretty real possibility that the person using it does not have an interconnect; all the information is obtained from the local database, so I can’t use any fany things like How to get the visitor’s location (for example, country) using javascript geolocation .

+4
source share
4 answers

I think the toLocaleDateString function uses local default data on the device.

try this code to check the output:

// America/Los_Angeles for the US
// US English uses month-day-year order
console.log(date.toLocaleDateString('en-US'));
// → "12/19/2012"

// British English uses day-month-year order
console.log(date.toLocaleDateString('en-GB'));
// → "20/12/2012"

// Korean uses year-month-day order
console.log(date.toLocaleDateString('ko-KR'));
// → "2012. 12. 20."

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleDateString('ar-EG'));
// → "٢٠‏/١٢‏/٢٠١٢"

// chinese
console.log(date.toLocaleDateString('zh-Hans-CN'));
// → "2012/12/20"
+7
source

Yes. It is pretty simple. You can use the date object as follows:

var d = new Date();
var mm = d.getMonth() + 1;
var dd = d.getDate();
var yy = d.getFullYear();

Then you should have the numbers necessary to form a string in any format.

var myDateString = yy + '-' + mm + '-' + dd; //(US)

Please note that this will give something like 2015-1-2, if the numbers are in single digits, if you need 2015-01-02, then you will need further conversion.

Also note that this will only give the “customer” date, i.e. date in the user system. It should be in your local time. If you need server time, you will have to have some kind of api to call.

+2
source

- :

var date = new Date(Date.UTC(2015, 0, 28, 4, 0, 0));
console.log(date.toLocaleDateString("nl",{year:"2-digit",month:"2-digit", day:"2-digit"}));

"28-01-15" Chrome (48.0.2564.116) .

Firefox just returns “01/28/2015”, and phantomJS returns “28/01/2015” regardless of language.

+1
source

Apparently, Date.prototype.toLocaleDateString () is not browser compatible. You can implement various options for the short date format, as described here: How is the JavaScript date format in relation to browser culture?

0
source

All Articles