0

I'm trying to do a calculation that is pre written in a variable (adding or taking away days from a given date) but I'm aware I'm going to need to some strip and replace to get this working and define the date formatting etc but am struggling along the way. In it's simplest form say If I have an actual string variable like this;

var newDate = 'Jul 10, 2018 + 1';

How can I output this as;

Jul 11, 2018

I've searched for a while but can't seem to work out how I can go about doing this, any help greatly appreciated. thanks

Joel Rosen
  • 157
  • 1
  • 11
  • 2
    Possible duplicate of [Incrementing a date in JavaScript](https://stackoverflow.com/questions/3674539/incrementing-a-date-in-javascript) – Fobos Jul 28 '18 at 15:57

4 Answers4

2

Here is the way you can do it:

  1. Split the String value by + to get the date and add number in array.

  2. Parse the string date to Date().

  3. Add the required days to new Date.

  4. Convert to required format by using toLocaleDateString

EDIT

For + and - numbers and multiple sums use eval

var inputDay=eval(inputStr[1].trim());

The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.

var newDate = 'Jul 10, 2018 + 1';
var inputStr=newDate.split(/\+(.+)/);
var inputDate=inputStr[0].trim();
var inputDay=eval(inputStr[1].trim());
var result=addDays(inputDate,inputDay);
console.log(result);

newDate = 'Jul 10, 2018 + 1 + - 2 + -3';
inputStr=newDate.split(/\+(.+)/);
inputDate=inputStr[0].trim();
inputDay=eval(inputStr[1].trim());
result=addDays(inputDate,inputDay);
console.log(result);

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  var options = {year: 'numeric',month: 'short', day: 'numeric'};
  return result.toLocaleDateString('en-US', options)
  

}
NullPointer
  • 6,137
  • 3
  • 22
  • 38
  • nice how can I wrap the result in another variable? instead of console.log for output? – Joel Rosen Jul 28 '18 at 16:18
  • it already in the **result** variable..The final output date is in **result** variable – NullPointer Jul 28 '18 at 16:18
  • Awesome! Okay.. what about my variable was something like this; Jul 05, 2018 + 1 + - 2 + -3 so basically lots of sums, will the above work with + and negative numbers and multiple sums? – Joel Rosen Jul 28 '18 at 16:21
  • It will work for + and negative numbers but single value as I am passing value direclty. However you can evaluate the expression after 1st + and then pass to it then it can work for multiple value – NullPointer Jul 28 '18 at 16:25
  • So close! Does your code work for either / or. As I don't know if the variable will have multiple sums, negative minus etc? – Joel Rosen Jul 28 '18 at 16:56
  • Thanks for your help, still cant get this to work but pretty sure this is the closest, probably my syntax somewhere – Joel Rosen Jul 28 '18 at 16:59
1

Use the method toLocalDateString() to format the date, this particular method gives you the option to set timezone and locale. This is with vanilla javascript. Using a library like moment.js gives you a lot more flexibility and options, not to mention more intuitive methods.

Edit : I've updated my answer based on your particular use case. This function will check whether you are adding or subtracting to/from a date and return a formatted date.

It's a little clunky in my opinion but I just threw it together. You can tweak it to your needs.

function checkString(dateString){

  let operator, number, date = null;
  let options = {year: 'numeric',month: 'short', day: 'numeric'};
  
  if( dateString.includes("+") ){
    operator = 'add';
  }else if( dateString.includes("-") ){
    operator = 'subtract';
  }
  
  switch(operator){
    case 'add':
      dateArr = dateString.split("+");
      number = parseInt(dateArr[1]);
      date = dateArr[0];
      var newDate = new Date(date);
      newDate.setDate(newDate.getDate() + number);
      return newDate.toLocaleDateString('en-US', options);
    case 'subtract':
      dateArr = dateString.split("-");
      number = parseInt(dateArr[1]);
      date = dateArr[0];
      var newDate = new Date(date);
      newDate.setDate(newDate.getDate() - number);
      return newDate.toLocaleDateString('en-US', options);
    default:
      return 'Unable to parse date';
  }
  
}

let formattedDate = checkString('July 10, 2018 + 1');
alert(formattedDate);
LegenJerry
  • 390
  • 2
  • 7
0

You'll want to use the Date object to extract specific data properties with a combination of their getter methods. toDateString() is a good start

0

This will work for you:

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var d = new Date("2018, 07, 10");

d.setDate(d.getDate() + 1);

Now to get your desired date get the Month, date, Full Year as below: document.getElementById("demo").innerHTML = months[d.getMonth()]+" "+d.getDate()+" , "+d.getFullYear();`