I want to adjust the Date object to always be 4 hours offset. How would I achieve this?
var d = new Date();
// d would be 4 hours in the past
Something like this:
d.setHours(d.getHours()-4);
Date.withOffset = function( offset ){
var r = new Date();
r.setHours(r.getHours()+offset);
return r;
};
var d = Date.withOffset( -4 )
// d would be 4 hours in the past
You may come up with a better name.
If you wish to break all javascript on your page you may of course use:
Date = function () {
var old = Date;
function broken() {
var r = new old();
r.setHours(r.getHours()-4);
return r;
}
broken.fix = function () {
Date = old;
};
return broken;
}();
You can then fix it by calling Date.fix()
You can create a date object with a particular date. Just subtract the correct milliseconds from the current time and pass that to the date function:
var d = new Date(new Date().getTime() - 1000*60*60*4);
or you can manually set the hours
var d = new Date();
d.setHours((12 + (d.getHours() - 4))%12)
Related
var startDateTime = '15.04.2019 00:15';
var endDateTime = '17.05.2019 18:35';
var checkDateTime = '16.04.2019 13:15';
function(checkDateTime, startDateTime, endDateTime) {
// need codes to return true or false,.
// check "checkDateTime" is between "startDateTime" to "endDateTime"
}
Try this code:
var startDateTime = getDate('15.04.2019 00:15');
var endDateTime = getDate('17.05.2019 18:35');
var checkDateTime = getDate('16.04.2019 13:15');
function isBetween(checkDateTime, startDateTime, endDateTime) {
return (checkDateTime >= startDateTime && checkDateTime <= endDateTime);
}
function toDate(str){
var [ dd, MM, yyyy, hh, mm ] = str.split(/[. :]/g);
return new Date(`${MM}/${dd}/${yyyy} ${hh}:${mm}`);
}
console.log(isBetween(checkDate,startDate,endDate));
To compare it one time falls between a time interval on the same day use: -
var startTime = "00:35";
var endTime = "18:15";
var checkTime = "13:00";
function getMinutes(timeString){
let [hh, mm] = timeString.split(":");
return parseInt(hh)*60 + parseInt(mm);
}
function isTimeBetween(checkTime,startTime,endTime){
checkTime = getMinutes(checkTime);
return (checkTime >= getMinutes(startTime) && checkTime <= getMinutes(endTime));
}
console.log(isTimeBetween(checkTime,startTime,endTime));
You can use new Date().getTime() to get the number of milliseconds since the Unix Epoch. So that you can compared the date/time with the result from this function. You can do sth like that:
return new Date(startDateTime).getTime() <= new Date(checkDateTime).getTime() <= new Date(endDateTime).getTime();
Check this out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
I would suggest to check if your checkDateTime is greater than your startDateTime and less then endDateTime.
function checkDateTime(checkDateTime, startDateTime, endDateTime) {
return (new Date(startDateTime) >= new Date(checkDateTime))
&& (new Date(checkDateTime) <= new Date(endDateTime));
}
Here is yet another option which adds the method directly to the Date prototype:
var startDateTime = new Date('04/15/2019 00:15');
var endDateTime = new Date('05/17/2019 18:35');
var checkDateTime = new Date('04/16/2019 13:15');
var outOfRangeDate_EARLY = new Date('01/16/2019 13:15');
var outOfRangeDate_LATE = new Date('06/16/2019 13:15');
Date.prototype.inRange = function(startDate, endDate){
var this_ms = this.getTime();
return ( this_ms >= startDate.getTime() && this_ms <= endDate.getTime() )
}
/* Tests */
console.log('expected: true', 'actual:', checkDateTime.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_EARLY.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_LATE.inRange(startDateTime, endDateTime))
This way, with any date you have var someDate, you can just call someDate.inRange(startDate, endDate). Sometimes, however, messing with the native prototypes can come back to haunt you if not careful. If so, having a separate function as answered by the others is very good.
Lastly, it's very important that the date strings are formatted properly before creating the Date objects, otherwise you'll encounter Invalid Date a lot. I hope this helps.
I have a form with a simple input type. I'm trying to define a function to check if the date is no more than 6 months older compared to date provided by the input type.
I know i have to convert the String provided by the input in a Date object to make this comparison and then work on get methods of Date object, but i can't figure out how to do this.
Current code:
$scope.compareDates = function(d1) {
d1 = new Date(d1); //convert String into date Object
var d = new Date(); // today date
d.setYear(d.getFullYear());
d.setMonth(d.getMonth() - 6);
if(d1 > d ) {
console.log("ok");
} else {
console.log("error");
}
}
EDIT:
I'm sorry, i forgot to add my input. Here it is:
<input class="form-control" type="text" placeholder="gg/mm/aaaa" ng-model="sStartDate" ng-change="change()">
Angular Controller:
$scope.sStartDate = '';
$scope.change = function(){
var startDt = $scope.sStartDate;
$scope.compareDates(startDt);
}
If I am reading your code correctly, your date format is days/month/year which is not valid format. You need to swap the month and days.
var parts = d1.split(),
dateStr = parts[1] + "/" + parts[0] + "/" parts[2],
d1 = new Date(d1),
d = new Date();
d.setMonth(d.getMonth() - 6);
if(d1 > d ) {
console.log("ok");
} else {
console.log("error");
}
What's about using d.getTime()?
$scope.compareDates = function(d1){
d1 = new Date(d1); //convert String into date Object
var d = new Date(); // today date
d.setMonth(d.getMonth() - 6);
if(d1.getTime() > d.getTime() ) {
console.log("ok");
} else {
console.log("error");
}
}
Regards.
I used momentjs for this in our app. It makes this process very easy and smooth.
// is6MonthsOld will be a boolean value
var is6MonthsOld = moment(d1).isBefore(moment().subtract(6, 'months'));
If you are comparing dates and not time, make sure to reset time in your date object using d1.setHours(0,0,0,0).
When you do new Date(), output is a datetime object, but when you do new Date(2015,6,19), only date is assigned and time is set to 00:00:00.
Following code depicts the same:
function compareDates(d1,d2){
return +d2 > +d1;
}
function compareDatesWithHoursReset(d1,d2){
d1.setHours(0,0,0,0);
d2.setHours(0,0,0,0);
return +d2 > +d1;
}
function main(){
var d1 = new Date();
var d2 = new Date(2015, 6, 19);
d1.setMonth(d1.getMonth() - 6)
console.log(d1);
console.log(d2);
console.log(compareDates(d2,d1))
console.log(compareDatesWithHoursReset(d2,d1))
}
main();
I'm trying to sucstract hours from datetime.
I tried with setHours and AddHours and both of the times in the debugger i see "undefined".
This is my function, everyting that i marked is things that i tried:
function timeLine(hours) {
var dt = new Date();
debugger;
//var calculatedDateTime = dt.setHours(dt.setHours() - (hours));
//var calculatedDateTime = dt.setHours(hours);
//var calculatedDateTime = dt.(hours);
//var calculatedDateTime = dt.AddHours(dt.AddHours() - (hours));;
$("#tblAlarms").find("tr").each(function (index) {
if (index === 0) return;
var filterColumn = $(this).find("td").eq(4);
if (Date.parse(filterColumn) > calculatedDateTime)
$(this).show();
else
$(this).hide();
}
This is where i set the hours:
onclick="timeLine(-12)">12
Can someone help me please?
Try
(dateNow - datePast) / 3600000
This will give you the number of hours.
and
new Date(date - hours * 3600000)
will substract an amount of hours from your date and give you the new date.
You can use the AddHours() to subtract the hours from Date by passing negative values.
DateTime dt = dt.AddHours(-6);
var d = new Date();
var hours = 12;
d.setHours(d.getHours() - hours);
alert(d);
Fiddle here
Use moment for any date/time calculations:
Example:
moment(date1).diff(date2,'minutes');
moment(date1).diff(date2,'days');
Hi i am trying to do a IF statement which allows the current date to be compared to the input date.. if the input date is below the current date it will be false.
I have got the date passing through my variable but it only stores the number so for example it compares day 9 to another day, which is not very reliable. I want the variable to take in the month and the year as well, meaning it can compare the ENTIRE DATE.
If there is a better way let me know.
Here is my code
if (this.element.find('#visitdate').length > 0) {
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
if (check < today) {
_errMsg = "Please enter a furture visit date";
return false;
} else {
return true;
}
}
Your line for today's date contains an error:
var today = new Date().getDate;
should be
var today = new Date().getDate();
format as mm/dd/yyyy
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
var today = new Date().getDate();
function isFromBiggerThanTo(dtmfrom, dtmto){
var from = new Date(dtmfrom).getTime();
var to = new Date(dtmto).getTime() ;
return from >= to ;
}
or using below
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
and compare
You can try this - it's working fine in my project -
Step 1
First Create javascript function as below.
Date.prototype.DaysBetween = function () {
var intMilDay = 24 * 60 * 60 * 1000;
var intMilDif = arguments[0] - this;
var intDays = Math.floor(intMilDif / intMilDay);
if (intDays.toLocaleString() == "NaN") {
return 0;
}
else {
return intDays + 1;
}
}
Step 2
-
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
var dateDiff = check .DaysBetween(today);
// it will return integer value (difference between two dates )
if(dateDiff > 0 ){ alert('Your message.......');}
You can have this much easier.
You dont need to check with getDate() property you can just compare 2 dates.
And also is not needed to initialize with hours, minutes and seconds the Date, you only need year, month and date.
Here you have your example simplified
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0]);
var today = new Date();
if (check < today) {
return false;
} else {
return true;
}
http://jsfiddle.net/wns3LkLv/
Try this:
var user="09/09/2014/5/30";
var arrdt= user.split("/");
var userdt = new Date(arrdt[2], arrdt[1] - 1, arrdt[0],arrdt[3],arrdt[4]);
var currdt = new Date();
if (userdt < currdt) {
alert("userdate is before current date"); //do something
}else{
alert("userdate is after current date"); //do something
}
Thanks for all your answers guys i have fixed it.
I used the getTime function instead of getDate.
Then the check variable had to have a -1 assigned to the month as it was going 1 month to high.
var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0).getTime();
Cheers
Given two Date() objects, where one is less than the other, how do I loop every day between the dates?
for(loopDate = startDate; loopDate < endDate; loopDate += 1)
{
}
Would this sort of loop work? But how can I add one day to the loop counter?
Thanks!
Here's a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren't an issue either.
var now = new Date();
var daysOfYear = [];
for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
daysOfYear.push(new Date(d));
}
Note that if you want to store the date, you'll need to make a new one (as above with new Date(d)), or else you'll end up with every stored date being the final value of d in the loop.
Based on Tom GullenĀ“s answer.
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var loop = new Date(start);
while(loop <= end){
alert(loop);
var newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
}
I think I found an even simpler answer, if you allow yourself to use Moment.js:
// cycle through last five days, today included
// you could also cycle through any dates you want, mostly for
// making this snippet not time aware
const currentMoment = moment().subtract(4, 'days');
const endMoment = moment().add(1, 'days');
while (currentMoment.isBefore(endMoment, 'day')) {
console.log(`Loop at ${currentMoment.format('YYYY-MM-DD')}`);
currentMoment.add(1, 'days');
}
<script src="https://cdn.jsdelivr.net/npm/moment#2/moment.min.js"></script>
If startDate and endDate are indeed date objects you could convert them to number of milliseconds since midnight Jan 1, 1970, like this:
var startTime = startDate.getTime(), endTime = endDate.getTime();
Then you could loop from one to another incrementing loopTime by 86400000 (1000*60*60*24) - number of milliseconds in one day:
for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
var loopDay=new Date(loopTime)
//use loopDay as you wish
}
Here simple working code, worked for me
var from = new Date(2012,0,1);
var to = new Date(2012,1,20);
// loop for every day
for (var day = from; day <= to; day.setDate(day.getDate() + 1)) {
// your day is here
console.log(day)
}
var start = new Date("2014-05-01"); //yyyy-mm-dd
var end = new Date("2014-05-05"); //yyyy-mm-dd
while(start <= end){
var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1);
var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate());
var yyyy = start.getFullYear();
var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd
alert(date);
start = new Date(start.setDate(start.getDate() + 1)); //date increase by 1
}
As a function,
function getDatesFromDateRange(from, to) {
const dates = [];
for (let date = from; date <= to; date.setDate(date.getDate() + 1)) {
const cloned = new Date(date.valueOf());
dates.push(cloned);
}
return dates;
}
const start = new Date(2019, 11, 31);
const end = new Date(2020, 1, 1);
const datesArray = getDatesFromDateRange(start, end);
console.dir(datesArray);
Based on Tabare's Answer,
I had to add one more day at the end, since the cycle is cut before
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var newend = end.setDate(end.getDate()+1);
var end = new Date(newend);
while(start < end){
alert(start);
var newDate = start.setDate(start.getDate() + 1);
start = new Date(newDate);
}
Didn't want to store the result in an array, so maybe using yield?
/**
* #param {object} params
* #param {Date} params.from
* #param {Date} params.to
* #param {number | undefined} params.incrementBy
* #yields {Date}
*/
function* iterateDate(params) {
const increaseBy = Math.abs(params.incrementBy ?? 1);
for(let current = params.from; current.getTime() <= params.to.getTime(); current.setDate(current.getDate() + increaseBy)) {
yield new Date(current);
}
}
for (const d of iterateDate({from: new Date(2021,0,1), to: new Date(2021,0,31), incrementBy: 1})) {
console.log(d.toISOString());
}
If you want an efficient way with milliseconds:
var daysOfYear = [];
for (var d = begin; d <= end; d = d + 86400000) {
daysOfYear.push(new Date(d));
}
Let us assume you got the start date and end date from the UI and stored it in the scope variable in the controller.
Then declare an array which will get reset on every function call so that on the next call for the function the new data can be stored.
var dayLabel = [];
Remember to use new Date(your starting variable) because if you dont use the new date and directly assign it to variable the setDate function will change the origional variable value in each iteration`
for (var d = new Date($scope.startDate); d <= $scope.endDate; d.setDate(d.getDate() + 1)) {
dayLabel.push(new Date(d));
}
Based on Jayarjo's answer:
var loopDate = new Date();
loopDate.setTime(datFrom.valueOf());
while (loopDate.valueOf() < datTo.valueOf() + 86400000) {
alert(loopDay);
loopDate.setTime(loopDate.valueOf() + 86400000);
}