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

2

I am using a datepicker , which uses the moment.js library. The calendar displays the date in local format, pt-br , as well as the value returned. I want to get this string and format in English (2018-03-20) format. OBs: using moment I could do so:

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

But I can not because he sends 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
    
asked by anonymous 20.03.2018 / 14:42

2 answers

8

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

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

Here is an 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'));

Here's 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>
    
20.03.2018 / 15:24
0

I believe the answer presented by Caique Romero answers the specific question of the bad author, would like to leave this answer 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-us in this case) to "en-US" however, the format "suggested" by the author YYYY- MM-DD is not the usual English language format that uses MM / DD / YYYY as the default language.

The following example represents the "correct" output if the intention is even 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() replaces the "bars" if this is even important.

It should be noted that the format of hours in "en-US" uses 24 hours while the "en-US" format only 12 so the output will always have "AM" or "PM" to indicate which time of day is being referenced.

The formatting of the English language also differs for Americans and British, the 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)

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

The following example uses UNIXTimeStamp obtained locally (pt-BR) and uses it to convert standard "en-US" and "en-GB" outputs (% with% to replace "

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 blogs, it is very common to have users from around the world, for example saving the already formatted date of a user's publication in the bank, as showing other users "spread" around the world. date of the post (fluently in their languages and times)? 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 timeZone option of replace() to simulate the local timezone of potential users around the world, in this case a Paulista a "Novayorkino" and a Londoner. >

As countries can have more than one timezone in a real environment, the correct timezone would be to get the user's local timezone (who is viewing / accessing a post):

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

In this way users "scattered" around the world can see exact date of when another user made a publication 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 strings already formatted you will have problems converting (formatting) to other outputs.

References

UnixTimeStamp: RFC2822 , #

JavaScript object toLocaleString() : Mozilla Docs

JavaScript Date() : Mozilla Docs

JavaScript Intl.DateTimeFormat() : Mozilla Docs

Language tags used in toLocaleString() follow BCP47

Complements:

20.03.2018 / 21:35