subtracting two dates via moment results in wrong year - javascript

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

Related

Javascript setting date not working ok Chrome

Here's an issue I'm getting setting a date with Javascript on Chrome
"17-09-2019"
var [day, month, year] = date.split('-');
undefined
day
"17"
month
"09"
year
"2019"
var set_date = new Date(parseInt(year), parseInt(month), parseInt(day));
undefined
console.log(set_date);
VM5577:1 Thu Oct 17 2019 00:00:00 GMT+0300 (East Africa Time)
undefined
So I have a date 17-09-2019 and point here is 09 is September but when I set the date I get back October.
Been scratching my head over this one for a while now. Not sure what's going on.
The months in javascript starts from 0. You just need to subtract 1 to your parseInt(month):
var date = "17-09-2019";
var [day, month, year] = date.split('-');
console.log(`${day}-${month}-${year}`)
var set_date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
console.log(set_date);
Set out this , month starting from index 0
var date = "17-09-2019"
var [day, month, year] = date.split('-');
month = month - 1;
var set_date = new Date(parseInt(year), parseInt(month), parseInt(day));
console.log(set_date); //Tue Sep 17 2019 00:00:00 GMT+0530 (India Standard Time)

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

Remove GMT+530(Indian standard Time) without changing current time in javascript

I am displaying current day,month,date,year and time like this
Mon Oct 24 2016 17:09:25 GMT+0530 (India Standard Time)​​​​​​​
but i need to display like this
Mon Oct 24 2016 17:09:25
my code in javascript:
var timestamp = new Date();
editor.insertHtml( 'The current date and time is: ' + timestamp.toString());
How can i do this please can anyone tell me how to do this.
Thank you
If you are open to add a library, you should use moment.js
console.log(moment().format('ddd MMM DD YYYY hh:mm:ss'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
If not, a small work around
var d = new Date().toString();
var index = d.lastIndexOf(':') +3
console.log(d.substring(0, index))
Note: moment approach is more preferred
var date = new Date();
var n = d.toLocaleString();
document.getElementById("demo").innerHTML = n;
This is work for me.
var timestamp = new Date();
console.log(
timestamp.toString().split('GMT')
)
// Mon Oct 25 2021 17:56:11 GMT+0530 (India Standard Time)`
the Output will be Mon Oct 25 2021 17:55:02
let today = new Date();
today = today.toString();
today = today.split('G')[0];
console.log(today);

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

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