Michael Miner
Michael Miner

Reputation: 964

Javascript Locale Date Conversions

I have a string coming into a function, this string is a date from Sweden and is formatted 2016 maj 01. Passed into this function is the country code for the locale sv-se. I need to convert the date string into a valid date object, to which I can then apply the locale.

This is for global date validation.

SO far I have

var date = new Date();
Intl.dateTimeFormat(locale, options).format(date);

I want to be able to have new Date("2016 maj 01") however since this is not English this is an invalid date. Can I using the locale convert this to a valid date object?

It was suggested my problem is similar to another. The way my problem is different is that I have the month coming in as the months abbreviated name. If the month was displayed numerically this would not be an issue

Upvotes: 0

Views: 1872

Answers (2)

Gopal Yadav
Gopal Yadav

Reputation: 368

I think you are trying to do the opposite of the method Date.prototype.toLocaleDateString(), which returns formatted string based on the passed Locale and options arguments. You can read more about it here.

Now, here you want to do the opposite of what toLocaleDateString method does, you want to give a formatted date string with a Locale, and you expect it to return a date object. To do so, you can check this post, I hope it can help you to get a head start.

Also, if you are comfortable to use external libraries then you can explore for localization libraries like moment.js

Upvotes: 0

Regis Portalez
Regis Portalez

Reputation: 4860

As I commented, it's probably a duplicate of an existing question. JavaScript Date object cannot be built from localized string.

However, you wan make your own Date builder from swedish:

Date.fromSwedish = (function() {
  var months = {
    'jan': 0,
    'feb': 1,
    'mar': 2,
    'apr': 3,
    'maj': 4 /*...*/
  };

  return function(s) {
    var splitted = s.split(' ');
    var year = splitted.length > 0 ? splitted[0] : 1970;
    var month = splitted.length > 1 ? months[splitted[1].toLowerCase()] : 0 ;
    var day = splitted.length > 2 ? splitted[2] : 1;
    return new Date(year, month, day);
  };
}());

document.write(Date.fromSwedish("2016") + "<br/>");
document.write(Date.fromSwedish("2016 feb") + "<br/>");
document.write(Date.fromSwedish("2016 maj 01") + "<br/>");

Upvotes: 1

Related Questions