0

I have this string:

16.12.2018

Then I create an object from it and add one day, like this:

var mindate = new Date(mindate.split('.').reverse().join(','));
if (mindate.getDay() == 0) { // If it is Friday  
    mindate.setDate(mindate.getDate() + 1);
}

The result is: Mon Dec 17 2018 00:00:00 GMT+0200 (Eastern European Standard Time)

Is it possible to return same string from new Date, aka 17.12.2018, without using additional libraries?

MorganFreeFarm
  • 3,811
  • 8
  • 23
  • 46
  • 1
    Just extract the date/month/year from the date object, and format it appropriately? – CertainPerformance Dec 14 '18 at 11:20
  • 1
    @CertainPerformance Yes, this is solution, but I looking for some method for format of dates in JS – MorganFreeFarm Dec 14 '18 at 11:21
  • 1
    It basically comes down to this: If there's a locale format that matches what you want, you can use `.toLocaleDateString( someLocale )`. Else you better off with writing your own formatting function as shown below and in the duplicates, since it'll be easier to work with than trying to force one of the toString functions to respect the format you want through their options. – Shilly Dec 14 '18 at 11:32
  • @Shilly Yeah, but I come from PHP where have very good options for formating of Date objects, so I looking for something like it, but .. :) – MorganFreeFarm Dec 14 '18 at 11:38

2 Answers2

2

Sure you can do the following :

function formatDate(date) {
  var monthNames = [
    "01", "02", "03",
    "04", "05", "06", "07",
    "08", "09", "10",
    "11", "12"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return day + '.' + monthNames[monthIndex] + '.' + year;
}

var mindate = "16.12.2018";
mindate = new Date(mindate.split('.').reverse().join(','));
if (mindate.getDay() == 0) { // If it is Friday  
    mindate.setDate(mindate.getDate() + 1);
}
console.log(formatDate(mindate))
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
2

Try this with mindate;

var dateString = mindate.getDate() + '.'+ Number(mindate.getMonth()+1)+'.'+ mindate.getFullYear();
Devinder
  • 127
  • 1
  • 10