2

I'm trying to create a function that converts the milliseconds to the date form which should be compatible to Turkish and formatted like "<2-digits of day>-<full name of month>-<4-digits of year>".

I've already tried the function .toLocaleDateString("tr-TR") but couldn't try the alternative libraries such as Momemtjs and Datejs that are server-included because I need this on the client-side. I've tried console.log() for every variable with or without .toString() and couldn't figure it out.

const dSelector = document.querySelectorAll(".date");
const formatDate = (de) => {
        var monthNames = [
          "Ocak", "Şubat", "Mart",
          "Nisan", "Mayıs", "Haziran", "Temmuz",
          "Ağustos", "Eylül", "Ekim",
          "Kasım", "Aralık"
        ];
        var date = new Date(de);
        var day = date.getDate();
        var monthIndex = date.getMonth();
        var year = date.getFullYear();
        return `${day}-${monthNames[monthIndex]}-${year}`;
}
dSelector.forEach((d) => {
    d.innerHTML = formatDate(d.innerHTML);
});

The expected output: "`<day>-<month>-<year>"

The actual output: "NaN-undefined-NaN"

3 Answers3

4

If you use the correct options argument for .toLocaleDateString(), you can get the format you want. Haven't found the option to add the dashes though, but a replace can fix that:

const date_input = document.querySelector( '#some_date' );
const options = {
  year: 'numeric',
  month: 'long',
  day: 'numeric'
};
const formatter = ms => new Date( ms )
  .toLocaleDateString("tr-TR", options )
  .replace( / /g, '-' );
  
// If we don't parse the string to a number, we get an invalid Date object:
const invalid_str = formatter( date_input.value );
console.log( invalid_str );

const valid_str = formatter( parseInt( date_input.value, 10));
console.log( valid_str );
<input id="some_date" value="1567180483137">
Shilly
  • 8,511
  • 1
  • 18
  • 24
  • This helped me a lot for the formatting but there's still a problem. I checked if ````d.innerHTML```` points to the milliseconds (any 13-digits long number in the range from 0 to 1,5*10^12 ) which seems valid to me. When I enter random milliseconds, I have valid dates but when it takes ````d.innerHTML```` as parameter, it returns ````NaN-undefined-NaN```` –  Aug 30 '19 at 15:50
  • `.innerHTML` returns a string. Did you parse it into a number before using `new Date( de )` ? I have updated my answer. – Shilly Aug 30 '19 at 15:58
2

Your function seems to work fine for me. Yo are probably inputting an unexpected date format.

formatDate('01/10/2019') ----> 10-Ocak-2018

while

formatDate('21/10/2019') ----> NaN-undefined-NaN

You can see under the WARNINGS section here the use of DD/MM/YYYY is undefined.

Orangel Marquez
  • 375
  • 2
  • 12
-1

There must be something wrong with your date variable. Check the input passed ("de" parameter). Maybe try d.innerText, it must be ISO format.

TemporaryName
  • 487
  • 5
  • 16