adding seconds to a datetime variable in node.js - node.js

I have following code:
var dbDate = '2013-11-15 12:51:18';
var seconds = 30;
I want to get date after adding the seconds in the same format. Like:
var resultDate = dbDate + seconds; //'2013-11-15 12:51:48'
How to get desired result?

var dbDate = '2013-11-15 12:51:18';
var seconds = 30;
var parsedDate = new Date(Date.parse(dbDate))
var newDate = new Date(parsedDate.getTime() + (1000 * seconds))
console.log(formatDate(newDate))
function formatDate(date){
return ('{0}-{1}-{3} {4}:{5}:{6}').replace('{0}', date.getFullYear()).replace('{1}', date.getMonth() + 1).replace('{3}', date.getDate()).replace('{4}', date.getHours()).replace('{5}', date.getMinutes()).replace('{6}', date.getSeconds())
}

I would make use of the moment library for this. You could then achieve what you want as follows:
var moment = require('moment');
var dateFormat = 'YYYY-MM-DD HH:mm:ss';
var dbDate = '2013-11-15 12:51:18';
var seconds = 30;
var resultDate = moment(dbDate).add('seconds', seconds).format(dateFormat);
This makes use of the moment #add() and #format().

Another approach:
var a;
/// create our date from our nicely formatted Y-m-d H:i:s string
a = new Date('2013-11-15 12:51:18');
/// add 30 seconds
a = new Date(a.getTime() + (30 * 1000));
/// use toISOString, it's the closest to Y-m-d H:i:s
a = a.toISOString();
/// modify ISO string to get Y-m-d H:i:s
a = a.split('.')[0].replace('T', ' ');
/// output!
console.log( a );

Related

Find time difference between 2 dates with days, hours and minutes

Let's suppose I have a array list with all these following data.
let events = {
["-1 19:00"],
["-1 20:00"],
["-1 17:00", "-1 23:00"],
["1 18:00"],
["2 18:00"],
["3 18:00"],
["4 18:00"],
["5 18:00"],
["6 18:00"],
["7 18:00"],
};
So, Here -1 represents every single day, Like every "sunday, monday" and so on. -1 = everyday, 1 = Monday, 2 = Tuesday and so on.
So, I want to calculate The time left from the current time to the nearest day with hours and mins inside the array. I'm really lacking idea on how I'm supposed to do it.
getTimeLeftTillDay(dayname, time) :any {
let d = new Date();
let coming = parseInt(dayname);
if(coming === -1) {
coming = d.getDay();
}
const day = d.getDay();
const targetDay = coming; // Someday
let dayOffset = targetDay - day;
if (dayOffset < 0) dayOffset += 7;
d = new Date(d.getTime() + (dayOffset * 24 * 3600 * 1000));
let timea = parseInt(time[0]);
let timeb = parseInt(time[1]);
d.setHours(timea);
d.setMinutes(timeb);
return d;
}
I tried to use the above code but it doesn't work as I expected. I'll really like help!
If relying on a 3rd-party library is ok for you, I'd use one of the many date-libs to perform the calculations. Here's how you could do it using date-fns:
import {addDays, formatDuration, intervalToDuration, setHours, setMinutes} from "date-fns";
const getTimeLeftTillDay = (dayName, time) => {
let daysToAdd = 0;
if (dayName !== '-1') {
daysToAdd = Number.parseInt(dayName);
}
const startDate = new Date();
let endDate = addDays(startDate, daysToAdd);
const [minutes, seconds] = time.split(":");
const hoursToSet = Number.parseInt(minutes);
endDate = setHours(endDate, hoursToSet)
const minutesToSet = Number.parseInt(seconds);
endDate = setMinutes(endDate, minutesToSet)
return customFormatDuration(startDate, endDate);
}
export const customFormatDuration = (start, end) => {
const durations = intervalToDuration({start, end})
return formatDuration(durations);
}
console.log(getTimeLeftTillDay("-1", "19:00"));
console.log(getTimeLeftTillDay("1", "02:00"));
console.log(getTimeLeftTillDay("7", "02:00"));
This prints the following on my machine (executed at 2:25 pm, CET):
4 hours 35 minutes
11 hours 35 minutes
6 days 21 hours 35 minutes
If you want to consider cases where the calculated time is before the current time and you want to treat them as "next-day" and handle days in the past in general, you can do:
const getTimeLeftTillDay = (dayName, time) => {
const startDate = new Date();
let dayToSet = getDay(startDate);
if (dayName !== '-1') {
dayToSet = Number.parseInt(dayName) - 1;
}
let endDate = new Date();
const [minutes, seconds] = time.split(":");
const hoursToSet = Number.parseInt(minutes);
endDate = setHours(endDate, hoursToSet)
const minutesToSet = Number.parseInt(seconds);
endDate = setMinutes(endDate, minutesToSet)
endDate = setDay(endDate, dayToSet);
if (isBefore(endDate, startDate)) {
endDate = addDays(endDate, 1);
}
return customFormatDuration(startDate, endDate);
}

Variable is undefined outside of the function

Can someone please help me out with this? I'm getting an error 'count is not defined' when executing the below code. I'm trying to create a countdown clock in node.js. If I log the timer variable inside the function it works but outside of the function, it is undefined.
const getOrder = async(request, response) => {
const data = await knex("orderbook_table").select()
const time_data = await knex("orderbook_table").select("timestamp")
console.log(time_data)
var timer;
setInterval(function count() {
for (var i = 0; i < time_data.length; i++) {
//console.log(tableRows[i]);
var entryDate = time_data[i].timestamp;
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
countDown = new Date(entryDate).getTime();
let now = new Date().getTime();
distance = countDown - now;
days = Math.floor(distance / (day));
hours = Math.floor((distance % (day)) / (hour));
minutes = Math.floor((distance % (hour)) / (minute));
seconds = Math.floor((distance % (minute)) / second);
timer = days + "d:" + hours + "h:" + minutes + "m:" + seconds + "s";
//console.log(timer);
}
}, 1000);
var orderStr = data;
count();
console.log(timer);
response.send({ orderStr });
//refresh()
The count function is defined and scoped under the setTimer, you should create the function as callback outside of setInterval then call within that setInterval the created function
You can give a look to this previously answered thread or to the documentation

Add Dates in a loop netsuite scripting

I am trying to print dates by adding more days to them by using nlapiAddDays() in a loop
var startdate = nlapiGetLineItemValue('item','custcol_startdt',i+1);
var enddate = nlapiGetLineItemValue('item','custcol_enddt',i+1);
var stringtodate1 = nlapiStringToDate(startdate);
var stringtodate2 = nlapiStringToDate(enddate);
//BELOW FORMULA I USED TO GET NUMBER OF MONTHS BETWEEN TWO DATES
var diff =(stringtodate2.getTime() - stringtodate1.getTime()) / 1000;
var diffMonths = Math.ceil(diff / (60 * 60 * 24 * 7 * 4)-1);
if(diffMonths > 1)
{
for(i=0; i <= diffMonths; i++)
{ var AddDays = 30;
var days = null;
if(i == 0)
{
days = stringtodate1;
}
else
{
days = nlapiAddDays(stringtodate1, AddDays);
}
}
nlapiLogExecution('DEBUG','days',days);
AddDays++;
}
here,if i becomes 1,30 days are added but when i becomes 2, 60 days should get added because of AddDays++ but it is not happening.30 days are added for every loop.
You are resetting AddDays to 30 at the top of the loop. You would need:
var AddDays = 30;
for(i=0; i <= diffMonths; i++)
{ ...

How to calculate difference between two dates using Node.js?

I need to calculate the datetime difference using the node.js. I am using the dateformat package to get current datetime format. My code is below:
var dateFormat = require('dateformat');
var prev_date=2017-08-09T19:00:58+0530;
var now = new Date();
var current_date=dateFormat(now, "isoDateTime");
Here I have already the previous date and also the current datetime also. I need to calculate the difference between two dates in hour, minute and second separately.
let firstDate = new Date("7/13/2016"),
secondDate = new Date("09/15/2017"),
timeDifference = Math.abs(secondDate.getTime() - firstDate.getTime());
console.log(timeDifference);
alert(timeDifference)
If you want the number of days between the two dates...
let differentDays = Math.ceil(timeDifference / (1000 * 3600 * 24));
console.log(differentDays);
alert(differentDays);
You could also use Moment.js https://momentjs.com/docs/
console.log(moment.utc(moment(firstDate,"DD/MM/YYYY HH:mm:ss").diff(moment(secondDate,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss"))
If you want to calculate day-difference between two dates you don't require any package. You can use simple JavaScript.
var date1 = new Date("08/09/2017");
var date2 = new Date("08/10/2017");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24)); //gives day difference
//one_day means 1000*60*60*24
//one_hour means 1000*60*60
//one_minute means 1000*60
//one_second means 1000
console.log(diffDays)
function date_diff(d1, d2, get_item)
{
var date1 = new Date(d1)
var date2 = new Date(d2)
var Difference_In_Time = date1.getTime() - date2.getTime();
switch (get_item) {
case 'month':
return Math.round(Difference_In_Time / (1000 * 3600 * 24 * 30));
case 'day':
return Math.round(Difference_In_Time / (1000 * 3600 * 24));
case 'hour':
return Math.round(Difference_In_Time / (1000 * 3600));
case 'minute':
return Math.round(Difference_In_Time / (1000 * 60));
case 'second':
return Math.round(Difference_In_Time / 1000);
default:
break;
}
}
var moment = require('moment');
diffDateAndTime(stratDate, endDate, startTime, endTime) {
let nowDate = moment(Date.now()).format("YYYY-MM-DD");
let nowTime = moment(Date.now()).format("YYYY-MM-DD HH:mm:ss");
let dateOfStart = moment(stratDate).format("YYYY-MM-DD");
let dateOfEnd =moment(endDate).format("YYYY-MM-DD");
let timeOfStart = moment(Date.now()).format("YYYY-MM-DD") + " " + moment(startTime).format("HH:mm");
let timeOfEnd = moment(Date.now()).format("YYYY-MM-DD") + " " + moment(endTime).format("HH:mm");
let diffDate, diffTime;
diffDate = (moment(dateOfStart).diff(nowDate) <= 0) && (moment(dateOfEnd).diff(nowDate) >= 0);
if (moment(dateOfStart).diff(nowDate) === 0) {
diffTime = (moment(timeOfStart).diff(nowTime) < 0)
diffDate = diffTime;
}
if (moment(dateOfEnd).diff(nowDate) === 0) {
diffTime = moment(timeOfEnd).diff(nowTime) > 0 diffDate = diffTime;
}
return diffDate;
}

Node JS for loop does not work

In node js, after running the for loop, descrip does not contain anything, no field written into the descrip array, why?
data = data['data'];
var course = data['course'];
data = data['sections'];
var descrip = new Array();
console.log(data.length);
for (var i = data.size - 1; i >= 0; i--) {
var data = data[i];
var section = data['section'];
var day = data['day'];
var date = data['date'];
var start = data['start_time'];
var end = data['end_time'];
var location = data['location'];
var res = 'Section: '+section+'\nDate: '+date+' '+day+'\nLocation: '+location+'\nStart: '+start+'\tEnd: '+end;
descrip.push(res);
};
Assuming you expect data to be an array, data.size - 1 will be -1 since data.size is null. So it will exit the loop immediately. You probably want data.length.
The length of an array in JavaScript is returned by the length property:
for (var i = data.length - 1; i >= 0; i--) {
// no block scope in JS, using data as a variable name here overwrites array
// var data = data[i];
var _data = data[i];
var section = _data['section'];
var day = _data['day'];
var date = _data['date'];
var start = _data['start_time'];
var end = _data['end_time'];
var location = _data['location'];
var res = 'Section: '+section+'\nDate: '+date+' '+day+'\nLocation: '+location+'\nStart: '+start+'\tEnd: '+end;
descrip.push(res);
};
Also, as pointed out in the comments by #Red Alert, you're overwriting your data variable in the for loop (JavaScript has no concept of block scope). I've renamed it _data, but you could probably come up with a more meaningful name to distinguish between the array and the element of the current iteration.

Resources