Add future time to date and compare - javascript

I apologize if this question has been asked already but I couldn't find it for my problem.
I have seen this but am not sure what the number it returns represents: Date() * 1 * 10 * 1000
I'd like to set a future moment in time, and then compare it to the current instance of Date() to see which is greater. It could be a few seconds, a few minutes, a few hours or a few days in the future.
Here is the code that I have:
var futureMoment = new Date() * 1 *10 * 1000;
console.log('futureMoment = ' + futureMoment);
var currentMoment = new Date();
console.log('currentMoment = ' + currentMoment);
if ( currentMoment < futureMoment) {
console.log('currentMoment is less than futureMoment. item IS NOT expired yet');
}
else {
console.log('currentMoment is MORE than futureMoment. item IS expired');
}

Javascript date is based on the number of milliseconds since the Epoch (1 Jan 1970 00:00:00 UTC).
Therefore, to calculate a future date you add milliseconds.
var d = new Date();
var msecSinceEpoch = d.getTime(); // date now
var day = 24 * 60 * 60 * 1000; // 24hr * 60min * 60sec * 1000msec
var futureDate = new Date(msecSinceEpoc + day);
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

var futureMoment = new Date() * 1 *10 * 1000;
becomes
var now = new Date();
var futureMoment = new Date(now.getTime() + 1 *10 * 1000);
I think you mean to add time. Not multiply it.

If you deal with time, there is a lot of tools to choose.
Try moment library.

Used following code to compare selected date time with current date time
var dt = "Thu Feb 04 2016 13:20:02 GMT+0530 (India Standard Time)"; //this date format will receive from input type "date"..
function compareIsPastDate(dt) {
var currDtObj = new Date();
var currentTime = currDtObj.getTime();
var enterDtObj = new Date(dt);
var enteredTime = enterDtObj.getTime();
return (currentTime > enteredTime);
}

Related

substract 5 minute from current Date and time javascript

I have problem while substracting time from current date. My Code looks like:
var d = new Date(),
year = d.getUTCFullYear(),
month = ('0'+(d.getUTCMonth()+1)).slice(-2),
day = ('0'+d.getUTCDate()).slice(-2),
hour = ('0'+d.getUTCHours()).slice(-2),
minute = ('0'+d.getUTCMinutes()).slice(-2),
second = ('0'+d.getUTCSeconds()).slice(-2);
var startDate = year+'/'+month+'/'+day+'-'+hour+':'+minute+':'+second;
console.log(startDate);
You can simply use like below
var fiveMinuteAgo = new Date( Date.now() - 1000 * (60 * 5) )
Get the milliseconds of the date variable, substract 5 minutes and create a new date object from it:
var d = new Date()
// d = Mon Feb 29 2016 08:00:09 GMT+0100 (W. Europe Standard Time)
var milliseconds = Date.parse(d)
// 1456729209000
milliseconds = milliseconds - (5 * 60 * 1000)
// - 5 minutes
d = new Date(milliseconds)
// d = Mon Feb 29 2016 07:55:04 GMT+0100 (W. Europe Standard Time)
If you are ready to use new date manipulation js called as moment js.
You can simply do it in one function as below:
moment().subtract(5, 'minutes');
Moment JS Docs
You could use like this
var original = new Date();
var subtract5min = new Date();
alert("before : " + original);
subtract5min.setTime(original.getTime() - 5*60*1000);
alert("after : " + subtract5min);
You can simply substract by
minute = ('0'+d.getUTCMinutes()).slice(-2)-5
var d = new Date(),
year = d.getUTCFullYear(),
month = ('0'+(d.getUTCMonth()+1)).slice(-2),
day = ('0'+d.getUTCDate()).slice(-2),
hour = ('0'+d.getUTCHours()).slice(-2),
minute = ('0'+d.getUTCMinutes()).slice(-2),
second = ('0'+d.getUTCSeconds()).slice(-2);
if (minute>=5)
minute = minute-5;
else {
minute = (parseInt(minute) + 60) - 5;
hour = hour - 1;
}
var startDate = year+'/'+month+'/'+day+'-'+hour+':'+minute+':'+second;
alert(startDate);

Javascript and mySQL dateTime stamp difference

I have a mySQL database in which I store the time in this format automatically:
2015-08-17 21:31:06
I am able to retrieve this time stamp from my database and bring it into javascript. I want to then get the current date time in javascript and determine how many days are between the current date time and the date time I pulled from the database.
I found this function when researching how to get the current date time in javascript:
Date();
But it seems to return the date in this format:
Tue Aug 18 2015 10:49:06 GMT-0700 (Pacific Daylight Time)
There has to be an easier way of doing this other than going character by character and picking it out from both?
You can build a new date in javascript by passing the data you receive from your backend as the first argument.
You have to make sure that the format is an accepted one. In your case we need to replace the space with a T. You may also be able to change the format from the back end.
Some good examples are available in the MDN docs.
var d = new Date("2015-08-17T21:31:06");
console.log(d.getMonth());
To calculate the difference in days you could do something like this:
var now = new Date();
var then = new Date("2015-08-15T21:31:06");
console.log((now - then)/1000/60/60/24);
You can select the difference directly in your query:
SELECT DATEDIFF(now(), myDateCol) FROM myTable;
the Date object has a function called getTime(), which will give you the current timestamp in milliseconds. You can then get the diff and convert to days by dividing by (1000 * 3600 * 24)
e.g.
var date1 = new Date()
var date2 = new Date()
var diffInMs = date2.getTime() - date1.getTime()
var diffInDays = diffInMs/(1000*3600*24)
Since none of the other answer got it quite right:
var pieces = "2015-08-17 21:31:06".split(' ');
var date = pieces[0].split('-');
var time = pieces[1].split(':');
var yr = date[0], mon = date[1], day = date[2];
var hour = time[0], min = time[1], sec = time[2];
var dateObj = new Date(yr, mon, day, hr, min, sec);
//if you want the fractional part, omit the call to Math.floor()
var diff = Math.floor((Date.now() - dateObj.getTime()) / (1000 * 60 * 60 * 24));
Note that none of this deals with the timezone difference between the browser and whatever you have stored in the DB. Here's an offset example:
var tzOff = new Date().getTimezoneOffset() * 60 * 1000; //in ms

JavaScript, get date of the next day [duplicate]

This question already has answers here:
Incrementing a date in JavaScript
(19 answers)
Closed 8 years ago.
I have the following script which returns the next day:
function today(i)
{
var today = new Date();
var dd = today.getDate()+1;
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
today = dd+'/'+mm+'/'+yyyy;
return today;
}
By using this:
today.getDate()+1;
I am getting the next day of the month (for example today would get 16).
My problem is that this could be on the last day of the month, and therefore end up returning 32/4/2014
Is there a way I can get the guaranteed correct date for the next day?
You can use:
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate()+1);
For example, since there are 30 days in April, the following code will output May 1:
var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000
var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000
See fiddle.
Copy-pasted from here:
Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
One-liner
const tomorrow = new Date(new Date().getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating
a new date):
var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow
= new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than
returning a new instance, so today.add(1, 'days') would modify today.
That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
Using Date object guarantees that. For eg if you try to create April 31st :
new Date(2014,3,31) // Thu May 01 2014 00:00:00
Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

How to get the number of weeks from a date in JS?

I need to find the number of weeks passed from a particular month, till date.
Like if its Nov, 2013 (as of today, 10th Jan, 2014) it should return 9 weeks.
Is there a way to find it?
Try the following:
function differenceInWeeks(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
}
The getTime function returns the number of milliseconds since 1970/01/01, the rest is just maths.
Try this:
function weeksSince(dateString){
var date = new Date(dateString);
var today = new Date();
return Math.floor((today-date)/(1000*60*60*24*7));
}
console.log(weeksSince("January 01, 2014"));
console.log(weeksSince("January 01, 2013"));
console.log(weeksSince("January 01, 2012"));
=> 1
=> 53
=> 105
Try This:
function weeks_between(date1, date2) {
// The number of milliseconds in one week
var ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms);
// Convert back to weeks and return hole weeks
return Math.floor(difference_ms / ONE_WEEK);
}
If you want them to be very precise(including days and time) then use these jquery libraries for that:
timeago
javascript pretty date
That's a little vague, and the other answers are correct - it's basically just maths once you understand how to get milliseconds out of a date...
Try this fiddle as a start;
http://jsfiddle.net/melchizidech/UGWe6/
Date.prototype.daysSince = function(newDate){
var difference = this.valueOf() - newDate.valueOf();
var msInDay = 1000 * 60 * 60 * 24;
var days = Math.floor(difference / msInDay);
return days;
};

Get date time for a specific time zone using JavaScript

It seems that JavaScript's Date() function can only return local date and time. Is there anyway to get time for a specific time zone, e.g., GMT-9?
Combining #​Esailija and #D3mon-1stVFW, I figured it out: you need to have two time zone offset, one for local time and one for destination time, here is the working code:
var today = new Date();
var localoffset = -(today.getTimezoneOffset()/60);
var destoffset = -4;
var offset = destoffset-localoffset;
var d = new Date( new Date().getTime() + offset * 3600 * 1000)
An example is here: http://jsfiddle.net/BBzyN/3/
var offset = -8;
new Date( new Date().getTime() + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )
"Wed, 20 Jun 2012 08:55:20"
<script>
var offset = -8;
document.write(
new Date(
new Date().getTime() + offset * 3600 * 1000
).toUTCString().replace( / GMT$/, "" )
);
</script>
You can do this in one line:
let d = new Date(new Date().toLocaleString("en-US", {timeZone: "timezone id"})); // timezone ex: Asia/Jerusalem
var today = new Date();
var offset = -(today.getTimezoneOffset()/60);
You can always get GMT time (so long as the client's clock is correct).
To display a date in an arbitrary time-zone, construct a string from the UTC hours, minutes, and seconds after adding the offset.
There is simple library for working on timezones easily called TimezoneJS can be found at https://github.com/mde/timezone-js.

Categories

Resources