Javascript setDate Confusion - javascript

I am trying to create a date object that is 90 days from a specified date for use in a date comparison, but am not getting the correct dates. I have isolated my problem to the code shown below.
var now = new Date();
var beforeNow = new Date();
var afterNow = new Date();
var myDate = new Date();
var beforeMyDate = new Date();
var afterMyDate = new Date();
beforeNow.setDate(now.getDate() - 90);
afterNow.setDate(now.getDate() + 90);
myDate.setFullYear(2011, 10, 22); // set to Nov 22, 2011
beforeMyDate.setDate(myDate.getDate() - 90); // set to 90 days before Nov 22, 2011
afterMyDate.setDate(myDate.getDate() + 90); // set to 90 days after Nov 22, 2011
The above is resulting in:
beforeMyDate: Fri Dec 23 2011 08:46:18 GMT-0800 (Pacific Standard Time)
myDate: Tue Nov 22 2011 08:46:18 GMT-0800 (Pacific Standard Time)
afterMyDate: Wed Jun 20 2012 08:46:18 GMT-0700 (Pacific Daylight Time)
Here's a fiddle: http://jsfiddle.net/LnmpR/9/
Any help would be appreciated. Thanks.

You have to pass the same base time to the beforeMyDate and afterMyDate Date instances. Currently, you're adding/removing 90 days of the current date (new Date() without parameters returns the current time).
Demo: http://jsfiddle.net/LnmpR/12/
var now = new Date();
var beforeNow = new Date();
var afterNow = new Date();
var myDate = new Date();
var beforeMyDate;
var afterMyDate;
beforeNow.setDate(now.getDate() - 90);
afterNow.setDate(now.getDate() + 90);
myDate.setFullYear(2011, 10, 22); // set to Nov 22, 2011
beforeMyDate = new Date(myDate); // Set base to myDate
afterMyDate = new Date(myDate); // Set base to myDate
beforeMyDate.setDate(myDate.getDate() - 90); // set to 90 days before Nov 22, 2011
afterMyDate.setDate(myDate.getDate() + 90); // set to 90 days after Nov 22, 2011
The values of beforeNow and afterNow might also be off by a few milliseconds, because all of them are new, parameterless instances of the Date object.

Related

How to get total minutes of difference between two dates using pure JavaScript

Updated My Question
How to get total minutes of difference between two dates using pure JavaScript when
Condition (1):: Same month, same year but date changes
newDate: 18/10/2016 0:50
oldDate: 17/10/2016 23:05
Condition (2):: Last date of current month and 1st date of next month
newDate: 1/11/2016 0:50
oldDate: 31/10/2016 23:05
Condition (3):: Last date of year and 1st date of new year
newDate: 1/1/2017 0:50
oldDate: 31/12/2016 23:05
Note: Please have a look newDate and oldDate to understand the conditions.
Thanks
Since you don't want to use a library for parsing date strings, you can write a simple function such as:
// Parse date string in "Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)" format
function parseDate(s) {
// Split into tokens
var b = s.match(/\w+/g) || [];
var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
// Determine offset in minutes
var offSign = /GMT+/.test(s)? -1 : 1;
var offset = b[8].substr(0,2)*60 + +b[8].substr(2,2);
// Create date, applying offset to minutes
var date = new Date(Date.UTC(b[3],
months.indexOf(b[1].toLowerCase()),
b[2],
b[4],
+b[5] + (offSign*offset),
b[6]));
return date;
}
var d = parseDate("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)")
console.log('UTC: ' + d.toISOString() + '\n' +
'Local: ' + d.toLocaleString());
Completed My Requirements with the below pure JavaScript code
In my code starttime and endtime are
//var startTime = localStorage.getItem("starttime");
//var endTime = new Date();
Example Here.
var startTime = new Date("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)");
var endTime = new Date("Sun Jan 1 2017 15:35:57 GMT+0530 (India Standard Time)");
var totalMiliseconds = endTime - startTime;
alert(totalMiliseconds);
//output:: 86400000
var totalSeconds = totalMiliseconds/1000;
alert(totalSeconds);
//output:: 86400
var totalMinuts = totalSeconds/60;
alert(totalMinuts);
//output:: 1440
var totalHours = totalMinuts/60;
alert(totalHours);
//output:: 24
And this fulfill my all 3 conditions.
Thank You For Your Support !!!

Does Javascript recognise leap years

I have the following snippet of code (actually I am using new Date() to get today (4th March 2016), but it won't be March for ever, so to be a sensible test I had made the date explicitly.
var n = new Date(2016,2,4);
var d = new Date (
n.getFullYear(),
n.getMonth(),
-1,
6,0,0);
console.log(d.toString());
when n is now (except it isn't) and d is a new date which I want to be the last day of the preceding month. I am NOT getting 29th February 2016 6:00am UTC, which is what I would have expected, instead I am getting 28th February.
This gives the same result in both Chrome and Iceweasel (Firefox). How should I find the last day of the previous month (especially, like this year when it is a leap year)
If it matters, I am in the GMT timezone.
That's because days are 1 based, not 0 based.
var march4 = new Date(2016, 2, 4);
var feb29 = new Date(
march4.getFullYear(),
march4.getMonth(),
0); // <-- go to the day before the first of the given month
console.log(feb29); // Mon Feb 29 2016 00:00:00 GMT-0700 (Mountain Standard Time)
For reference, if you pull the same trick for April to March, you'll get March 31st.
var april = new Date(2016, 3, 4);
var march = new Date(
april.getFullYear(),
april.getMonth(),
0);
console.log(march); // Thu Mar 31 2016 06:00:00 GMT-0600 (Mountain Daylight Time)
In fact, it recognizes
If you try this, it works:
Date (2016, 2, 0);
It brings to me Mon Feb 29 2016 00:00:00 GMT-0300
Instead of -1, try 0:
var n = new Date(2016,2,1);
var d = new Date (
n.getFullYear(),
n.getMonth(),
0,
6,0,0);
console.log(d.toString());

javascript getTime() returns greater value for older date compared to new date

javascript getTime() returns the number of milliseconds form midnight Jan 1, 1970 and the time value in the Date Object. but,
new Date('Wed Sep 16 2105 05:30:00 GMT+0530').getTime()
// returns 4282502400000
new Date('Tue Oct 26 2015 05:30:00 GMT+0530').getTime()
// returns 1445817600000
Shouldn't the value retuned by the later (Tue Oct 26 2015 05:30:00 GMT+0530) be greater.
I want to find the list dates between a given date (inform of timestamp) and today. I wrote the code below with the assumption that the value returned by getTime() for older dates will always be lesser than newer dates.
var timestamp = new Date('9/15/2105, 12:00:00 AM').getTime();
var startDate = new Date(timestamp);
// Date.UTC() to avoid timezone and daylight saving
var date = new Date(Date.UTC(startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()
));
var currentDay = new Date();
var currentDayTimestamp = new Date(Date.UTC(currentDay.getFullYear(),
currentDay.getMonth(),
currentDay.getDate()
)).getTime();
// day in millisec, 24*60*60*1000 = 86400000
date = new Date(date.getTime() + 86400000);
var dates = [];
console.info(date + ' : ' + date.getTime());
console.info(new Date(currentDayTimestamp) + ' : ' + currentDayTimestamp);
while(date.getTime() <= currentDayTimestamp) {
var dateObj = {
date: date.getUTCDate(),
month: date.getUTCMonth() + 1,
year: date.getUTCFullYear()
}
dates.push(dateObj);
date = new Date(date.getTime() + 86400000);
}
console.info(JSON.stringify(dates));
OUTPUT:
Wed Sep 16 2105 05:30:00 GMT+0530 (IST) : 4282502400000
Tue Oct 27 2015 05:30:00 GMT+0530 (IST) : 1445904000000
[]
The problem is a typo in your dates. One has the year 2105 which is much larger than 2015.

setDate with getDate + n returns today's date + n

I want d2 to be d1 + 14 days, instead it's todays' date + 14 days.
<script type="text/javascript">
var d1 = new Date(2014, 7, 1);
var d2 = new Date();
d2.setDate(d1.getDate() + 14);
// d1 = Fri Aug 01 2014 00:00:00 GMT+0100 (GMT Daylight Time)
document.write("d1 = " + d1);
document.write("<br></br>")
// today's date is 16-04-2014
// d2 = Tue Apr 15 2014 17:36:03 GMT+0100 (GMT Daylight Time)
document.write("d2 = " + d2);
</script>
How can I make d2 = d1 + 14 days?
setDate, somewhat surprisingly, sets the day-of-the-month of the existing instance. Since you've initialized d2 with today, you're just changing the day-of-month for that date, not taking on any other aspect of d1.
You probably want:
var d1 = new Date(2014, 7, 1); // A specific date
var d2 = new Date(d1); // Clone that date
d2.setDate(d1.getDate() + 14); // Move forward 14 days
That gives us August 1st for d1, and August 15th for d2.
Another option is:
var d1 = new Date(2014, 7, 1);
var d2 = new Date(d1.getFullYear(), d1.getMonth(), d1.getDate() + 14);
Both of those work even when you're going past the end of the month, btw.
Complete example of the second option: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Date plus 14 days</title>
<style>
body {
font-family: sans-serif;
}
</style>
</head>
<body>
<script>
(function() {
var d1, d2;
display("Starting with August 1st:")
d1 = new Date(2014, 7, 1);
d2 = new Date(d1.getFullYear(), d1.getMonth(), d1.getDate() + 14);
display("d1 = " + d1);
display("d1 = " + d2);
document.body.appendChild(document.createElement('hr'));
display("Starting with August 20th:")
d1 = new Date(2014, 7, 20);
d2 = new Date(d1.getFullYear(), d1.getMonth(), d1.getDate() + 14);
display("d1 = " + d1);
display("d1 = " + d2);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
You're making a new Date (today) for d2 but only changing the day, this should work:
var d1 = new Date(2014, 7, 1);
var d2 = new Date(2014, 7, d1.getDate()+14);
d1 is a date in August, d2 is today. You are setting d2 to today + 14 days. The proper result is below:
var d1 = new Date(2014, 7, 1);
var d2 = new Date(d1.setDate(d1.getDate() + 12));
Only put getTime() function inside d2 Date() function,
Check this Demo jsFiddle
JavaScript
var d1 = new Date(2014, 7, 1);
var d2 = new Date(d1.getTime());
d2.setDate(d1.getDate() + 14);
// d1 = Fri Aug 01 2014 00:00:00 GMT+0100 (GMT Daylight Time)
document.write("d1 = " + d1);
document.write("<br></br>")
// today's date is 16-04-2014
// d2 = Tue Apr 15 2014 17:36:03 GMT+0100 (GMT Daylight Time)
document.write("d2 = " + d2);
Result
d1 = Fri Aug 1 00:00:00 UTC+0530 2014
d2 = Fri Aug 15 00:00:00 UTC+0530 2014

Getting current time from the date object

function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(2), // get only two digits
month = datePart[1], day = datePart[2];
document.write(new Date(day+'/'+month+'/'+year));
}
formatDate ('2010/01/18');
When i print this i get Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time) but the system is actually 3:42 P.M
Use the current date to retrieve the time and include that in the new date. For example:
var now = new Date,
timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'),
dat = new Date('2011/11/30 '+timenow);
you must give the time:
//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11"));
//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11 23:23"));
What do you want? Just the time? Or do you want to define a format? Cu's the code expects this format for date: dd/mm/yyyy, changed this to yyyy/mm/dd
Try this:
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0],
month = datePart[1], day = datePart[2],
now = new Date;
document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds()));
}
formatDate ('2010/01/18')
Output:
Mon Jan 18 2010 11:26:21 GMT+0100
Passing a string to the Date constructor is unnecessarily complicated. Just pass the values in as follows:
new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10))
You're creating a Date() object with no time specified, so it's coming out as midnight. if you want to add the current date and time, create a new Date with no arguments and borrow the time from it:
var now = new Date();
var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10),
now.getHours(), now.getMinutes(), now.getSeconds())
No need to strip the last two characters off the year. "2010" is a perfectly good year.

Categories

Resources