0

How I can change the date format from yyyy.mm.dd to dd.mm.yyyy in javascript?

For example, I want to convert the date 1880.07.15 to 15.07.1880

function declOfNum(number, titles) {
    cases = [2, 0, 1, 1, 1, 2];  
    
    return number + " " +titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]];  
}

function birthDateToAge(b) {
    var n = new Date(), b = new Date(b),
     age = n.getFullYear() - b.getFullYear();
 
    return n.setFullYear(1972) < b.setFullYear(1972) ? age - 1 : age;
}

document.write( declOfNum(birthDateToAge("1880.07.15"), ['год', 'года', 'лет']) );

Thanks in advance.

marsze
  • 11,092
  • 5
  • 33
  • 50
  • 2
    Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Saransh Kataria Sep 18 '18 at 10:36
  • I'm sorry for this reply, but could you please change my script based on your example? I try to do many different examples, but I haven't enough knowledge for this... I will be very grateful for this. – Denys Kulii Sep 18 '18 at 10:40

1 Answers1

0

You can simply achieve your requirement like this.

change_format = function(date){
  var date_element = date.split('.');
  var reverse_date_element =date_element.reverse();
  return reverse_date_element.join('.');
}
console.log(change_format("1880.07.15"));

/*--------------- or ---------------------*/

change_date_format = function(date){
  var date_string = date.split('.').join('-');
  var date = new Date(date_string);
  return ((date.getDate()).toString().length > 1 ? date.getDate()  : '0'+ (date.getDate() + 1 ) )+'.'+ ((date.getMonth()).toString().length > 1 ? date.getMonth() + 1 : '0'+ (date.getMonth() + 1 ) ) + '.' + date.getFullYear()  ;
}
console.log(change_date_format("1880.07.15"));
Flames
  • 851
  • 7
  • 22
  • I want to change format inside javascript. I need to use inside JS format of data dd.mm.yyyy. But as default I need to use yyyy.mm.dd – Denys Kulii Sep 18 '18 at 11:11
  • The first function is fine, the second is not. "YYYY-MM-DD" will be treated as UTC so for the period of the local UTC offset, it will show the wrong date, either a day behind or a day ahead depending on whether the offset is east or west. – RobG Sep 18 '18 at 23:28