Click here to Skip to main content
15,898,729 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
JavaScript
var date=new Date();
var enDate=date.toLocaleDateString("en-US");
console.log(enDate);
var deDate=date.toLocaleDateString("de-DE");
console.log(deDate);


I can create date format with culture but can we revert back to that converted enDate or deDate to javascript date format again.


What I have tried:

javascipt
var date=new Date(enDate);
var date=new Date(deDate);
//or
var date=Date.parse(enDate);
//It returns invalid date
Posted
Updated 11-Feb-19 23:29pm
Comments
Richard MacCutchan 12-Feb-19 4:00am    
Look at the actual strings and see what they contain. Are those valid date strings in Javascript?
itsathere 12-Feb-19 7:15am    
All would be valid but conversion to date happen on region basis. If I will try to convert another region format into my region then it will return invalid date.
Richard MacCutchan 12-Feb-19 11:21am    
Dates and times should always be stored as UTC values. The only time you need to "regionise" them is when you print or display them in text format.

1 solution

function stringFormatToNewDate(date) {
    var dd = 0, mm = 0, yyyy = 0;
    var splittedFormat = [];
    var splittedDate = [];
    $.each(dateSeperators, function (index, item) {
        splittedFormat = __dateFormat.split(item);
        splittedDate = date.split(item);
        if (splittedFormat.length > 1 && splittedDate.length > 1) {
            return false;
        }
    });

    for (var i = 0; i <= splittedFormat.length; i++) {
        switch (splittedFormat[i]) {
            case "dd":
            case "d":
                dd = splittedDate[i];
                break;
            case "mm":
            case "m":
                mm = splittedDate[i];
                break;
            case "yyyy":
                yyyy = splittedDate[i];
                break;
        }
    }
    return new Date(yyyy, mm - 1, dd);
}
 
Share this answer
 
Comments
MadMyche 12-Feb-19 8:48am    
How does this determine which culture to apply?
itsathere 12-Feb-19 10:37am    
You have neither understand the question nor you have readout the question carefully that's why you are asking these question. Just read the question carefully and here is the link for you https://www.nuget.org/packages/jquery-globalize/
MadMyche 12-Feb-19 11:15am    
I understand your question and your code perfectly fine. And it is a perfect example of why dates should be kept as a Date until it is being displayed. "02/12/2019" and "12.02.2019" can both provide valid dates in either culture

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900