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?

4
  • 1
    Just extract the date/month/year from the date object, and format it appropriately? Commented Dec 14, 2018 at 11:20
  • 1
    @CertainPerformance Yes, this is solution, but I looking for some method for format of dates in JS Commented Dec 14, 2018 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. Commented Dec 14, 2018 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 .. :) Commented Dec 14, 2018 at 11:38

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

3 Comments

('0'+monthIndex).slice(-2) will 0 pad for you without an array.
@kabanus your answer would give 17.11.2018 and not 12 but yeah I got your point that it can be simplified :)
@MorganFreeFarm happy to help :)
2

Try this with mindate;

var dateString = mindate.getDate() + '.'+ Number(mindate.getMonth()+1)+'.'+ mindate.getFullYear();

1 Comment

Glad to see it worked :0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.