Find date difference in node.js [duplicate] - node.js

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

Related

date range validation by month in nodejs moment.js

I am trying to validate or check the date range by passing month and year, If date range come under the given month range between, then it would be valid else error.
month = "04, 06, 2022"; // from-month, to-month, year
date = "12-05-2022" // DD-MM-YYYY
from month = 04
to month = 06
year = 2022
I read the documentation but didn't achive the goal.
I want if I am passing this data below -
month = "04, 06, 2022"; // from-month, to-month, year
date = "12-07-2022" // DD-MM-YYYY => error
date = "12-05-2022" // DD-MM-YYYY => success
let value = '12-05-2022'; //DD-MM-YYYY
let check = moment(value,'DD-MM-YYYY', true).isValid();
console.log(check) //returns true
return check
Try to use a range to check if the date corresponding to value is contained:
const year = 2022;
const fromMonth = 4;
const toMonth = 6;
const startDate = new Date(year, fromMonth, 12);
const endDate = new Date(year, toMonth, 15);
const value = '12-05-2022';
const check = moment().range(startDate, endDate).contains(new Date(value));
console.log(check);

convert 13 digit time code to date and time stamp using moment js and get the difference between them

I have start time and end time as follows
var starttime=1631108701000
var endtime=1631116762000
var sessionstart=moment.unix(startTime);
var sessionend=moment.unix(endTime);
var ms = moment(sessionend,"DD/MM/YYYY HH:mm:ss").diff(moment(sessionstart,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var timeelapsed = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
goal is to display the starttime and endtime with proper date time stamp and disply the difference between then like 2hours16minutes53seconds or 02:16:53.The above code returns faulty data. How do I fix it?
The below code worked for me
var sessionstart= moment.unix(startTime/1000).format("DD/MM/YYYY HH:mm:ss");
var sessionend= moment.unix(endTime/1000).format("DD/MM/YYYY HH:mm:ss");
var ms = moment(sessionend,"DD/MM/YYYY HH:mm:ss").diff(moment(sessionstart,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var timeelapsed = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
By default moment.unix() expects in seconds so we need to divide by 1000 and format as per requirement.
You could also have a look at this approach. First convert unix epoch milliseconds to seconds. Then use moment's diff function to calculate the respective units. Notice that I am adding corresponding units after each diff to get the accurate difference.
const startTime = "1631108701000";
const endTime = "1631116762000";
// Converting epoch milliseconds to seconds
const startUnixTime = moment.unix(startTime / 1000);
const endUnixTime = moment.unix(endTime / 1000);
// hour difference
const hourDiff = endUnixTime.diff(startUnixTime, "hours");
startUnixTime.add(hourDiff, "hours");
// minute difference
const minDiff = endUnixTime.diff(startUnixTime, "minutes");
startUnixTime.add(minDiff, "minutes");
// second difference
const secDiff = endUnixTime.diff(startUnixTime, "seconds");
// Actual Input dates
const startDate = moment(startUnixTime).format("DD-MM-YYYY hh:mm:ss");
const endDate = moment(endUnixTime).format("DD-MM-YYYY hh:mm:ss");
console.log("Input start date", startDate);
console.log("Input end date", endDate);
// Difference in hours, minutes, seconds
console.log(hourDiff, minDiff, secDiff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Set default date and time [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I am using Material-UI and this is their example code.
However I need the defaultValue to be today's current date and time; how can I go about this?
<TextField
id="datetime-local"
label="Next appointment"
type="datetime-local"
defaultValue="2017-05-24T10:30"
className={classes.textField}
InputLabelProps={{'
shrink: true,
}}
/>
I have tried to use something like this, however the issue is if month and day are 1-9 then how single digits and not double digits which means it won't set.
const currentdate = new Date();
const datenow = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDay() + "T"
+ currentdate.getHours() + ":"
+ currentdate.getMinutes();
You could do something like this.
const d = new Date();
const year = (d.getFullYear()).toString();
const month = ((d.getMonth()) + 101).toString().slice(-2);
const date = ((d.getDate()) + 100).toString().slice(-2);
const hours = ((d.getHours()) + 100).toString().slice(-2);
const mins = ((d.getMinutes()) + 100).toString().slice(-2);
const datenow = `${year}-${month}-${date}T${hours}:${mins}`;

How to get month in MM and date in dd format in nodejs

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

Get previous date in node.js

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

Resources