how to add days to datetime in javascript? - javascript

I have date and time format datetimepicker. I would like to add number of days to the datetime
inputdattime will be picked from datetimepicker
input datetime = Friday, October 23rd 2015, 12:00:00 am
output should be if i add 2 days sunday, oct 25 2015 12:00:00 am
how to achieve this
var deal_from_date = new Date();
var numberOfDaysToAdd = 7;
var date1 = deal_from_date.setDate(deal_from_date.getDate() + numberOfDaysToAdd);
actual Output should be
"dddd, MMMM Do YYYY, h: mm:ss a"
Sun Oct 25 2015 12:00:00
current output is:
Sun Oct 25 2015 12:54:06

setDate() method can be used to add days to a date
var today=new Date('23/10/2015');
var in_a_day=new Date(today).setDate(today.getDate()+2);
Try this code :-
var d = new Date('oct 25 2015 12:00:00 pm');
d.setDate(d.getDate() + 2)
alert(d);
output is :- Tue Oct 27 2015 12:00:00 GMT+0530 (IST)

Related

subtracting two dates via moment results in wrong year

Hey folks running into a problem with dates that I would love an extra set of eyes on. Any help would be appreciated.
Problem: I have a future event which will occur on a certain date, when I subtract the future event date from the current date I get a year that is in the past and an extra day.
let evenDate = "12 08 2019, 12:00 am";
let eventFormat = "MM DD YYYY, h:mm a";
const futureEvent = moment(evenDate, eventFormat).utc();
const now = moment().utc();
const timeDiff = moment(futureEvent - now).utc(); // also tried futureEvent.diff(now)
let daysLeft: moment(timeDiff).format('D') - 1; // have to subtract 1
console.log('futureEvent:', futureEvent);
// Sun Dec 08 2019 00:00:00 GMT-0700 (Mountain Standard Time)
console.log('now:', now);
// Wed Dec 04 2019 10:18:26 GMT-0700 (Mountain Standard Time)
console.log('timeDiff:', timeDiff);
// Sun Jan 04 1970 06:41:33 GMT-0700 (Mountain Standard Time)
let evenDate = "12 08 2019, 12:00 am";
let eventFormat = "MM DD YYYY, h:mm a";
const futureEvent = moment(evenDate, eventFormat);
const now = moment();
const timeDiff = moment.duration(futureEvent.diff(now));
let daysLeft = timeDiff.asDays();
const disp = document.getElementById("display");
disp.innerText = daysLeft.toFixed(); // 3.0123
console.log("futureEvent:", futureEvent.toString());
Same code i just get rid of .utc()s. used .duration() and for getting dates used .asDays().
Pen

How to set time with AM PM in Javascript Date Object

Say that I have DateTime in this format Fri Feb 02 2018 00:00:00 GMT+0530 (IST)
And from the time picker plugin getting the time 1:10am or 2:30pm in this format.
I am not sure how to calculate and combine/add them both to produce this result:
Fri Feb 02 2018 01:10:00 GMT+0530 (IST) or Fri Feb 02 2018 14:30:00 GMT+0530 (IST)
I wish if there was something to do as simple as this:
new Date(dateString).setHours(1:10am)
Seems like you need to parse it on your own:
function parseDaytime(time) {
let [hours, minutes] = time.substr(0, time.length -2).split(":").map(Number);
if (time.includes("pm") && hours !== 12) hours += 12;
return 1000/*ms*/ * 60/*s*/ * (hours * 60 + minutes);
}
To add it to a date:
new Date(
+new Date("Fri Feb 02 2018 00:00:00 GMT+0530")
+parseDaytime("1:20pm")
);
Here is a simple function to do what your after.
It basically splits the time using a regex, and then calls setHours & setMins, adding 12 hours if pm is selected.
The example below takes the current datetime, and sets 1:10am & 2:40pm..
function setHours(dt, h) {
var s = /(\d+):(\d+)(.+)/.exec(h);
dt.setHours(s[3] === "pm" ?
12 + parseInt(s[1], 10) :
parseInt(s[1], 10));
dt.setMinutes(parseInt(s[2],10));
}
var d = new Date();
console.log(d);
setHours(d, "1:10am");
console.log(d);
setHours(d, "2:40pm");
console.log(d);
You can parse the time string into hours & minutes, adjust the hours according to am/pm & set it to the date object then:
var dateString = 'Fri Feb 02 2018 00:00:00 GMT+0530 (IST)';
var hoursString = '2:30pm';
var parts = hoursString.replace(/am|pm/, '').split(':')
var hours = parseInt(parts[0]) + (hoursString.indexOf('pm') !== -1 ? 12 : 0);
var minutes = parts[1];
var date = new Date(dateString);
date.setUTCHours(hours, minutes);
console.log(date); // in your local time
console.log(date.toUTCString()); // in UTC (i.e. without timezone offset)
(Note setHours / setUTCHours mutates date object but returns unix timestamp of the updated datetime.)

adding two datetime in javascript

I am getting datetime as inputs using multiple timepickers in AngularJS. I want to add all the time inputs(dynamic) to give me a total duration.
e.g: if i input
Date {Wed Feb 03 2016 02:07:44 GMT+0530 (India Standard Time)}
Date {Wed Feb 03 2016 05:09:05 GMT+0530 (India Standard Time)}
It should return
Date {Wed Feb 03 2016 07:16:49 GMT+0530 (India Standard Time)}
Here is my code:
https://jsfiddle.net/nitishhardeniya/ytndyuck/
Using moment
var moment = require('moment');
var d1 = moment("Wed Feb 03 2016 02:07:44 GMT+0530", "ddd MMM DD YYYY HH:mm:ss Z");
var d2 = moment("Wed Feb 03 2016 05:09:05 GMT+0530", "ddd MMM DD YYYY HH:mm:ss Z");
var dur1 = moment.duration(d1.format("HH:mm:ss"));
var dur2 = moment.duration(d2.format("HH:mm:ss"));
var totalDur = dur1 + dur2;
var temp = d1.clone();
temp.startOf('day').add(totalDur);
console.log(temp.format()); // 2016-02-03T07:16:49+05:30
console.log(temp.format("ddd MMM DD YYYY HH:mm:ss Z")); // Wed Feb 03 2016 07:16:49 +05:30
var difference = date2 - date1;
var newDate = new Date(date2.getTime() + difference);
Try using Date.parse() method. It converts date to timestamp.
var time1 = new Date('2013-08-12 10:30');
var time2 = new Date('2013-08-12 12:30');
var time3 = new Date('2013-08-12 1:15');
var result = (Date.parse(time1) - Date.parse(time2)) + Date.parse(time3);
var resultTime = new Date(result);
alert(resultTime)
Fiddle

How to format Friday, October 23rd 2015, 12:00:00 am to particular format datetime string?

I am using bootstrap datetimepicker have to get the datetime and add days to it
var get_date_time = Friday, October 23rd 2015, 12:00:00 am
format get_date_time to oct 25 2015 12:00:00 am how to format
How to format this to
var d = new Date('oct 25 2015 12:00:00 am');
d.setDate(d.getDate() + 2)
alert(d);
output should be
example
Tuesday, October 27th 2015, 12:00:00 am
How to achieve this?
You need to do the following...
Get your date var d = new Date('Oct 25 2015 12:00:00 am').
Then use d.getTime() to get total time in milliseconds. Then for each day you wish to add, add 3600000 to it. Then create a new date from that var newDate = new Date(1445758146777).
var d = new Date('Oct 25 2015 12:00:00 am');
var milisecs = d.getTime();
var oneDay = 3600000;
// Add one day to the date...
milisecs += oneDay;
var newDate = new Date(milisecs)
Then format it accordingly :-)
I have used moment.js http: //momentjs.com/ to convert particular format
var get_date_time = Friday, October 23rd 2015, 12:00:00 am
using moment js i have formatted to date like the below
alert(moment(get_date_from,'dddd, MMMM Do YYYY, h:mm:ss a').format("MMM DD YYYY h:mm:ss a"));
then i have followed like this to add number of days calculation
var date1 = deal_from_date.setDate(deal_from_date.getDate() + 2);

Convert UTCString to yyyy-mm-dd

I am trying UTCString to above format. I can able to convert, problem is after conversion it shows a day before.
var newDate = this.getCellDate(target);
console.log(newDate); --> Dec 05 2014 00:00:00 GMT+0800 (Malay Peninsula Standard Time)
cstDate = newDate.toISOString();
console.log(cstDate); -- > 2014-12-04 --- > **Expected --> 2014-12-05**
Use Date.UTC() method
var now = new Date(), // my date Thu Dec 04 2014 13:02:15 GMT+0300 (RTZ 2 (зима))
year = now.getFullYear(),
month = now.getMonth(),
day = now.getDay(),
hours = now.getHours(),
minutes = now.getMinutes(),
utcDate;
utcDate = new Date(Date.UTC(year, month, day, hours, minutes)); // Thu Dec 04 2014 16:02:00 GMT+0300 (RTZ 2 (зима))
Ext.Msg.alert('UTC Date', Ext.Date.format(utcDate, 'Y-m-d'));
Look at this "Thu Dec 04 2014 16:02:00" - i got utc time(+3 hours)
Fiddle example
Yeah i got the solution. I should not toISOString. instead i need to use toLocaleDateString
custdate = newDate.toLocaleDateString();
dueDate= custdate.split("/").reverse().join("-");

Categories