I have to calculate the previous day to select data from a DB for reporting. It worked until 2016-06-30 but failed at the 1st of July. Instead of getting the date for 2016-06-30 (at the 1st) I got 2016-05-31. My function is called once a day using node-schedule and looks like this:
cron.scheduleJob({hour: 0, minute: 5}, function () {
nowDate = new Date();
fromDate.setDate(nowDate.getDate() - 1);
toDate.setDate(nowDate.getDate() - 1);
logger.info("Started daily reporting ('"+fromDate.getFullYear() + "-" + (fromDate.getMonth() + 1) + "-" + fromDate.getDate() + " 00:00:00'"+" - '"+toDate.getFullYear() + "-" + (toDate.getMonth() + 1) + "-" + toDate.getDate() + " 23:59:59')");
proc.run(fromDate, toDate, function (error) {
if (error) {
logger.error(error);
} else {
logger.info("Finished daily reporting");
}
});
});
So the output at the 1st of July was:
Started daily reporting ('2016-5-31 00:00:00' - '2016-5-31 23:59:59'
Any idea why my calculation of the previous day failed?
The problem is with the fromDate and toDate getting declared as a global variable. These dates will get initialized as the day where the application runs, and in your loop you are trying to subtract 1 day off the datetime where this application first started.
Your application may work for the day where it runs but not on subsequent days. To fix the problem the dates will have to be initialized within the cron.scheduleJob function.
cron.scheduleJob({hour: 0, minute: 5}, function () {
let yesterdayDate = new Date();
yesterdayDate.setDate(yesterdayDate.getDate() - 1);
proc.run(/*from date=*/yesterdayDate, /*to date=*/yesterdayDate, function (error) {
if (error) {
logger.error(error);
} else {
logger.info("Finished daily reporting");
}
});
});
If you are intending to do more dates calculation or timezone handling and is looking for an easy reliable way of doing, use moment.js. It has already been tested and proven by many others in the JS community.
Example of subtracting a day off today's date;
"use strict";
var moment = require('moment');
for(let i = 1; i <= 5; i++){
console.log('lessed ' + i +' day since today = ' + moment().subtract(i, "days").format("DD-MM-YYYY"));
}
Output:
lessed 1 day since today = 02-07-2016
lessed 2 day since today = 01-07-2016
lessed 3 day since today = 30-06-2016
lessed 4 day since today = 29-06-2016
lessed 5 day since today = 28-06-2016
Anyway as pointed in the chat the .getDate() implementation has no issue and it works. Here is a little experiment made by me.
// Today is 3rd july 2016
nowDate = new Date();
nowDate.setDate(nowDate.getDate() - 1);
nowDate.setDate(nowDate.getDate() - 1);
nowDate.setDate(nowDate.getDate() - 1); // Before deduct = 1st July.
console.log("Started daily reporting ('"+nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + "-" + nowDate.getDate() + " 00:00:00'");
console.log(nowDate.toDateString());
Output:
Started daily reporting ('2016-6-30 00:00:00' Thu Jun 30 2016
Related
I am coding in NodeJs and have to create a filename which have date and time appended. The format should be "metadata_yyymmdd_his.json". I am struggling to get the date in dd and month in MM format.
Below is the code that I have written as of now.
const dateObj = new Date();
const month = (`0${dateObj.getUTCMonth() + 1}`).slice(-2);
const date = (`0${dateObj.getUTCDate()}`).slice(-2);
const metadataFileName = 'metadata_' + dateObj.getUTCFullYear() + month + date + "_" + dateObj.getUTCHours() + dateObj.getUTCMinutes() + dateObj.getSeconds() + '.json'
How can I get the date and month prepended with 0 if it is single digit?
EX: if month is April then the result should be 04
If you're in node, don't try to roll your own datetime parsing/formatting: install and then require something that's been written specifically for that purpose, and has been tested extensively so you can rely on it working properly. A common package for that is moment.js, using its .format() function
const now = moment.now();
const formatted = moment().format("MM-DD") // or whatever other formatting you need
I have a table that contains a year column, but the generated model does not seem to be able to search by year as I would expect.
Year model:
integer (Year) {
description (Description for Year)
}
Autogenerated js:
var dates = require('dates')
exports.timeToMili = timeToMili
function timeToMili(time) {
//TODO consider zone offset
var timeStr
if (time instanceof Object && "hour" in time) {
var hour = ("amPm" in time && String(time.amPM) == 'Pm') ? Number(time.hour) + 12 : Number(time.hour)
var minute = ("minute" in time && time.minute ? time.minute : "00")
//sanity check
timeStr = hour + ":" + (String(minute).length < 2 ? "0" + minute : minute)
return dates.ZonedDateTime.parseTime(timeStr, "H:mm").getMillisFromEpoch()
}
return null //TODO error handling
}
This training worked:
[g:CO2Concentration] Show the CO2 concentration for (1967)[v:Year]
The key was finding that "Year" was the correct Node to select.
I am creating a script using node that will grab records created in the last half an hour from a PostgreSQL database. I have:
var query = client.query("SELECT * FROM users WHERE created_at>'2015-9-16 20:04:17'");
Now, my issue is that I want the created_at>'2015-9-16 20:04:17' to actually search for records created in the last half hour using a variable I have called time. The variable time is set to the last half hour:
var currentdate = new Date();
var diff=30;
var time = new Date(currentdate.getTime() - diff*60000);
var day=time.getDate();
var month=time.getMonth()+1;
var year=time.getFullYear();
var hours=time.getHours();
var minutes=time.getMinutes();
var seconds=time.getSeconds();
var time=year + '-' + month + '-' + day + ' ' + hours+':'+minutes+':'+seconds;
How do I change the query so that it searches for date>time? Originally I thought I could write:
var query = client.query("SELECT * FROM users WHERE created_at>'$time'");
You can avoid all the calculation on the client side, and instead compute the required start-time in SQL:
var query = client.query("SELECT * FROM users "
+ "WHERE created_at > (NOW() - INTERVAL 30 MINUTES)");
(I split the string purely for readability here; you don't need to do the same)
I suggest you to do:
var time=year + '-' + month + '-' + day + ' ' + hours+':'+minutes+':'+seconds;
client.query("SELECT * FROM users WHERE created_at >'" + time + "'");
i'm not sure if this is possible but i can't find any clue of doing this with multidatespicker..
i'm creating a web booking system which need to allow customer to select any booking date which they like.
But now my client was requesting to create package like weekly package(4 times per month), biweekly(1 times per 2 weeks) and etc..For weekly example.. when customer choose tuesday of that week.. the rest of 6 days all will be disable.. and for biweekly.. for that week and next week will be disable..
Thousand appreciate for someone who could help :)
I have the same issue: in my booking project the user must can select days range but also week range (only from Saturday to Saturday).
I managed the selection of the week on onSelect() event of multiDatesPicker() init function: by click on a day of the week MultiDatesPicker auto-select the relative week from Saturday to Saturday.
Unfortunately, for me the open issue is the hover event, because I want MultiDatesPicker also hover the week by pass hover the days of a week, not only select it, so the user could have perception to really choose weeks, not days.
It's singular that MultiDatesPicker has not a onHover() function to manage the "pre-selection"/hover event.
var autoselectRange = [0, days_range];
$('.multidatespicker-wrapper').multiDatesPicker({
numberOfMonths: [1, 2],
minDate: 1,
firstDay: 1,
mode: 'daysRange',
onSelect: function(dateText, inst) {
var selectedDate = $.datepicker.parseDate($.datepicker._defaults.dateFormat, dateText);
from_date = new Date(moment(dateText, "MM/DD/YYYY").format("YYYY-MM-DD"));
to_date = new Date (moment(dateText, "MM/DD/YYYY").add('days', days_range - 1).format("YYYY-MM-DD"));
if (weekRange) {
// Setting of Start and End of the week
if (from_date.getDay() == 6) numDaysToWeekStart = 0; // because Saturday in this case it is Start of the week
else numDaysToWeekStart = from_date.getDay() + 1;
from_date = new Date(from_date.setDate(from_date.getDate() - numDaysToWeekStart));
to_date = new Date(to_date.setDate(to_date.getDate() - numDaysToWeekStart));
// Setting of the days of the week
date = new Date(from_date);
weeks = [];
while (date <= to_date) {
weeks.push(new Date(date));
date.setDate(date.getDate() + 1);
}
// Selection of the days of the week/weeks in MDP Calendar
$(this).multiDatesPicker('resetDates', 'picked');
$(this).multiDatesPicker('addDates', weeks);
}
// Any more controls
},
autoselectRange: autoselectRange,
pickableRange: days_range,
// any more settings });
I hope It could be a help; if you have some idea to manage hover event and you can share it. Thanks
This question already has answers here:
Time difference in Nodejs?
(7 answers)
Closed 8 years ago.
How to find the date of 15 days ago from the current date using Node.js?
For Eg:
Current date is - 10/JAN/2015
15 days ago is - 26/DEC/2014
There's really no need for a third party library. You can get the current time in ms and subtract 15 days worth of milliseconds from it and feed that to a new Date object:
var today = new Date();
var old = new Date(today.getTime() - (15 * 24 * 60 * 60 * 1000));
Working test harness: http://jsfiddle.net/jfriend00/f12Lfvyx/
Use moment.js
var moment = require( 'moment' );
var date1 = moment( '25/12/2014', 'DD/MM/YYYY' );
var date2 = moment( '10/01/2015', 'DD/MM/YYYY' );
var diffInMillis = date2.diff( date1 );
var diffDuration = moment.duration( diffInMillis );
console.log( diffDuration.toString() );
// to find a date 15 days ago, substract duration of 15 days
var rightNow = moment();
var before15Days = rightNow.substract( 15, 'days' );
console.log( rightNow.format( 'DD/MM/YYYY' );
console.log( before15Days.format( 'DD/MM/YYYY' );
use moment.js
moment().subtract('days', 15); // subtracts 7 days to current date
This link helps you...