0

Now i have the english locale en-US and french locale fr-CA. How can i format a english date 05/31/2018 to french date 31/05/2018?

Varrian
  • 191
  • 1
  • 1
  • 12
  • 1
    Maybe [`Date.prototype.toLocaleString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) – Pointy Jun 03 '19 at 22:19
  • There is also the [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat) functionality. – Heretic Monkey Jun 03 '19 at 22:22
  • "en-US" is an ISO 639 language code. The term "locale" is a misnomer. – RobG Jun 03 '19 at 22:50

1 Answers1

-1

If you are trying to catch the actual datetime, you can do only setDate() with this function on your code:

 function setDate(dt){

    if(dt = "NaN"){
      var date = new Date();
    }else{
      var date = new Date(dt);
    }

    var language = navigator.language;
    var dateTime;

    var day = date.getDate();
    var month = date.getMonth()+1;
    var year = date.getFullYear();

    if(day < 10){
      day = `0${day}`;
    }

    if(month < 10){
      month = `0${month}`;
    }

    if(language == 'en-US'){
      dateTime = `${day}/${year}/${month}`;
    }else{
      dateTime = `${day}/${month}/${year}`;
    }

    return dateTime;
  }

But, if you have an especific datetime, you can add on console.log(setDate("05/31/2018"));.

This function will return you the date formated.

  • The code has errors, and it doesn't answer the OP's question. – RobG Jun 03 '19 at 22:53
  • Where are the errors? – Assis Duarte Jun 03 '19 at 23:01
  • https://codepen.io/anon/pen/PvLzeZ?editors=1111 – Assis Duarte Jun 03 '19 at 23:04
  • `if (dt = "NaN")` will always resolve to true, it doesn't test whether *dt* is NaN and if corrected to `dt == NaN`, will always be false as NaN isn't equal to anything, even NaN (hence [*isNaN*](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN)). `new Date(dt)` is a bad idea, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results). – RobG Jun 03 '19 at 23:19
  • True, sorry to bored you, thanks for this. – Assis Duarte Jun 03 '19 at 23:35
  • No problem, most of the benefit of StackOverflow is to those who post answers. It's often more beneficial than asking a question. :-) – RobG Jun 04 '19 at 05:24