0

I need to parse a date format in javascript, however the date format is variable.

I have the dateformat in a variable:

function getLocaleDateString(locale) {

var formats = {
    "ar-SA": "dd/MM/yy",
    "bg-BG": "dd.M.yyyy",
    "ca-ES": "dd/MM/yyyy",
    "zh-TW": "yyyy/M/d",
     ....
return formats[locale]
}

var dateformat = getLocaleDateString(locale);

so for example I may have a date string dd/mm/yyyy 30/01/2015 or it may be mm/dd/yyyy 01/30/2015

I need to parse this to a date object in javascript.. But as I'm unsure of the format, I don't know how I can parse it..

9
  • stackoverflow.com/questions/2587345/javascript-date-parse/… Commented Apr 8, 2014 at 4:08
  • Ive seen that, but its no good because it requires u programming in the date format... for example Date.parse("1/1/1970") will only work for mm/dd/yyyy and the other one requies u knowing the date format while programming Commented Apr 8, 2014 at 4:10
  • Regardless of how you intend to parse the string, you must know the format and tell the parser as it is impossible to reliably determine the format from a string unless it is one of the unambiguos formats (e.g. ISO 8601). Commented Apr 8, 2014 at 4:11
  • 1
    30/01/2015 and 01/30/2015 this can be easily detected and can be parsed.. What about dates like 03/01/2015 and 01/03/2015? Do you think it is easy to detect without knowing the date format? Commented Apr 8, 2014 at 4:12
  • 1
    Blind help : stackoverflow.com/a/20898946/1636522. Commented Apr 8, 2014 at 4:47

2 Answers 2

0

If you don't want to write it by hand you'll need a library. moment.js is a good choice.

Sign up to request clarification or add additional context in comments.

Comments

-1

Given I will have the dateforamt in a string ie "dd-mm-yyyy" you can easily parse the string using a function like:

function parseString(s) {
  s = s.split(/\D+/);
  return new Date(s[2], --s[1], s[0],0,0,0,0);
}

console.log(parseString('04-03-2014')); // Tuesday, 4 March 2014

1 Comment

Another down–voter without the courage to explain their convictions. Perhaps they were annoyed over a comment or other answer and, unable to defend their position, vent their spleen by randomly down–voting an unrelated answer. Or maybe they have a valid point, I'll never know. I'm baffled as to why "use library X" is a better answer (or at least, less deserving of a down vote), perhaps the downovter thinks all questions should be answered like that. I agree that that isn't defendable, hence no comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.