Convert date from DD/MM/YYYY to YYYY-MM-DD in Javascript

Asked

Viewed 40,794 times

4

I’m wearing a datepicker, using the library moment.js. Calendar displays date in local format, pt-br, as well as the value returned. I want to take this string and format in English format (2018-03-20). Note: using Moment I could do so:

moment('02/03/2018 00:00:00').format('YYYY-MM-DD HH:mm:ss')

But I can’t, because he gives me this warning:

Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments: 
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 01/01/2017 10:08:28, _f: undefined, _strict: undefined, _locale: [object Object]
Error
  • Remove hours, it’s only the date

  • 1

    Example: moment(testDate).format('YYYY-MM-DD');

  • if the warning bothers you why not just use console.clear()? If not you will end up falling into the problem of using a shotgun to kill ant

  • sorry my datepicker uses hours, should have put there

  • @Peace because when I do the parse it gives the warning and returns me invalid date

  • 1

    @Leandrorr, nothing wrong, it works perfect here: http://jsfiddle.net/r42jg/2668/

  • Possible duplicate of How to format date in javascript?

  • @Caiqueromero your comment is wrong, Leandro’s question is about formatting date with the Moments library.

  • @Caiqueromero is not duplicate because the question you mentioned is doing the opposite, from English to Portuguese.

  • See the @Caiqueromero reply, and see if you solved the problem, don’t forget to accept the answer as accepted.

  • @Leandrorr seems to me that you are trying to internationalize your bad software/ system, the format YYYY-MM-DD is not common for English language users (en-US) who follow (use) the format MM/DD/YYYY. I believe that if the goal is to "internationalize" the software should follow the standard language format.

  • @Lauromoraes the format I am trying to parse, is to store in my SQL Server database.

Show 7 more comments

4 answers

18


You can take the string and break it parts using the method split() to separate the parts using / as parameter and then sort it in the format you want.

In the example below on both day and month I concatenate a zero and catch the last two elements of the sequence using the function Slice(-2) so I guarantee you will be with 2 digits printing the desired result.

Follow example function:

function FormataStringData(data) {
  var dia  = data.split("/")[0];
  var mes  = data.split("/")[1];
  var ano  = data.split("/")[2];

  return ano + '-' + ("0"+mes).slice(-2) + '-' + ("0"+dia).slice(-2);
  // Utilizo o .slice(-2) para garantir o formato com 2 digitos.
}


console.log(FormataStringData('02/03/2018'));

Follow a solution using the Moment.js library:

/*
Você deve informar para o moment 
o formato de entrada, ou seja, como está 
a string com sua data antes de 
formatá-la pois internamente ele
fará um parse e chamará um new Date().

Fonte: http://momentjs.com/docs/#/parsing/string/
*/
var data = moment("02/03/2018", "DD/MM/YYYY");

//Feito isso basta definir o formato de saída:
console.log(data.format("YYYY-MM-DD"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>

  • Correct me if I’m wrong, bad output in "en-US" format Intl.DateTimeFormat which is used by javascript should not be: 03-02-2018 ? The way it is is not the format "en-US"

  • To Intl describes that: American English uses MM/DD/YYYY a small difference (use case) British using DD/MM/YYYY

  • Not by name, by shape of output even... it seems to me the answer satisfies the bad question, the question itself seems to "want to create an American format" YYYY-MM-DD when actually the American format used by Intl.DateTimeFormat is MM/DD/YYYY

  • I will suggest this to the author

6

I believe the answer presented by Caique Romero I would like to leave this reply in order to enrich the topic.

It seems to me that the author seeks to internationalize his software/system and convert a locally formatted user input (en-BR in this case) to "en-US" however, the format "suggested" by the author YYYY-MM-DD is not the usual format of the English (American) language that uses by default MM/DD/YYYY.

The following example represents the "correct" output if the intention is internationalization:

let dateObj = new Date('02/03/2018 00:00:00')

let dateString = dateObj.toLocaleString('en-US', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute:'2-digit',
    second:'2-digit'
}).replace(/\//g, '-')

console.log(dateString)

A simple replace() replaced "bars" if this is really important.

Note that the format of hours in "en-BR" uses 24 hours while the format "en-US" only 12 so the output will always have "AM" or "PM" to indicate which period of the day is being referenced.

The formatting of the English language also differs as to Americans and British, British use the format DD/MM/YYYY as in this example:

let dateObj = new Date('02/03/2018 00:00:00')

let dateString = dateObj.toLocaleString('en-GB', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute:'2-digit',
    second:'2-digit'
}).replace(/\//g, '-')

console.log(dateString)

British use 24-hour format so there is no "AM/PM" in the output, looks like our "en-br" the only difference is in a comma after the date.

The following example uses locally obtained Unixtimestamp (en-BR) and uses it to convert to standard "en-US" and "en-GB" outputs (replace() to replace the "bars")

let UNIX = Date.now()

console.log('UnixTimeStamp: ', UNIX)
console.log('Unix String (UTC): ', new Date(UNIX))

function Format(timestamp, lang) {

   let dateObj = new Date(timestamp)
   
   return dateObj.toLocaleString(lang, {
       year: 'numeric',
       month: '2-digit',
       day: '2-digit',
       hour: '2-digit',
       minute:'2-digit',
       second:'2-digit'
   }).replace(/\//g, '-')
   
}

console.log('formato pt-BR: ', Format(UNIX, 'pt-BR'))
console.log('formato en-US: ', Format(UNIX, 'en-US'))
console.log('formato en-GB: ', Format(UNIX, 'en-GB'))

The above example only displays UNIX-based formatting, it does not express the difference between Timezones.

In open systems such as posts (blogs) it is very common to have users from various parts of the world, for example saving the already formatted date of a user’s publication in the bank, how to show other users "scattered" around the world the date of the post (in a fluid manner in their languages and schedules)? Saving the date of publication in Unixtimestamp this is possible:

let UNIX = Date.now()

console.log('UnixTimeStamp: ', UNIX)
console.log('Unix String (UTC): ', new Date(UNIX))

function Format(timestamp, lang, tz) {

   let dateObj = new Date(timestamp)
   
   return dateObj.toLocaleString(lang, {
       timeZone: tz,
       year: 'numeric',
       month: '2-digit',
       day: '2-digit',
       hour: '2-digit',
       minute:'2-digit',
       second:'2-digit'
   }).replace(/\//g, '-')
   
}

console.log('formato pt-BR: ', Format(UNIX, 'pt-BR','America/Sao_Paulo'))
console.log('formato en-US: ', Format(UNIX, 'en-US', 'America/New_York'))
console.log('formato en-GB: ', Format(UNIX, 'en-GB', 'Europe/London'))

The above example uses the option Timezone of toLocaleString() to simulate the local Timezone of possible users around the world, in this case, a Paulista a "Novayorkino" and a Londrino.

As countries may have more than one Timezone in a real environment the correct would be to take the user’s local Timezone (which is seeing/accessing a publication):

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

This way users "scattered" around the world can see exact date of when another user made a post taking into account their local time.


NOTE:

The best way to work with dates for formatting (internationalization) is to use Unixtimestamp references because they can be formatted for any output. When using already formatted strings you will have trouble converting (formatting) to other outputs.


References

Unixtimestamp: RFC2822, ISO8601 section 15.9.1.15

Javascript object Date(): Mozila Docs

Javascript Intl.DateTimeFormat(): Mozila Docs

Javascript toLocaleString(): Mozila Docs

Language tags used in toLocaleString() follow the BCP47

Complemetos:

1

It’s simple!

moment('08/04/2018 00:00:00', 'DD/MM/YYYY HH:mm:ss', true).format('YYYY-MM-DD HH:mm:ss')

0

function formata_data(data) { // dd/mm/yyyy -> yyyy-mm-dd
    data_formatada = data.substr(6,4) + '-' + data.substr(3,2) + '-' + data.substr(0,2) + ' 00:00:00';
    return new Date(data_formatada);
}
  • This answer is not valid for the question raised because the object of the question is the library moment.js and not the native kind Date.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.