i have two dates, where the first one is the date start and the second one is the date end.
I have to translate this in number of Years, Months and Days.
Example:
const start = moment(new Date('2021-03-03'))
const end = moment(new Date('2022-03-03'))
const difference = moment.duration(end.diff(start))
const days = difference.days() //30
const months = difference.months() // 11
const years = difference.years() // 0
the result is:
{"days":30,"months":11,"years":0}
But my expected behavior is:
{"days":0,"months":0,"years":1}
How can I reach this?
To achieve your expected behavior just simply change your code:
from this:
const end = moment(new Date('2022-03-03'))
to this:
const end = moment(new Date('2022-03-03')).add('1', 'days')
This will give: {"days":0,"months":0,"years":1}
Final full updated code:
const start = moment(new Date('2021-03-03'))
const end = moment(new Date('2022-03-03')).add('1', 'days')
const difference = moment.duration(end.diff(start))
const days = difference.days() // 0
const months = difference.months() // 0
const years = difference.years() // 1
I think it is because at 03/03 it will always remain at least a millisecond to complete the year.
For example i try to use .startOf('d') and .endOf('d') and this is the results:
const start = moment(new Date('2021-03-03')).startOf('d')
const end = moment(new Date('2022-03-03')).endOf('d')
moment("2021-03-03T00:00:00.000")
moment("2022-03-03T23:59:59.999")
Alex.
Related
Firs time I faced with such issue, I have (the working case):
const weekendsInMonth = (anydate) => {
let today_tmp = new Date();
let today = new Date(today_tmp.getTime() - today_tmp.getTimezoneOffset()*60*1000);
let lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0).getDate();
let myDate = today;
//some other function code
Once I do modification to function (only anydate IN variable, second row):
const weekendsInMonth = (anydate) => {
let today_tmp = new Date(anydate);
let today = new Date(today_tmp.getTime() - today_tmp.getTimezoneOffset()*60*1000);
let lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0).getDate();
let myDate = today;
//some other function code
The NodeJs says only:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
And nothing happens, actually there is more rows in output should come, like web server started at port, etc. No warnings, no erros and app page could not be viewev in browser (only error - ERR_CONNECTION_REFUSED). What am I doing wrong?
I am importing this function to my server.js as:
const {daysInThisMonth, weekendsInMonth, } = require("./src/core/functions");
Same time the other similar function does not fault:
const daysInThisMonth = (date) => {
var now = new Date(date);
return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
}
I figured out it. The problem was that date must be defined in this case:
const weekendsInMonth = (anydate = new Date) => {
let today_tmp = new Date();
let today = new Date(today_tmp.getTime() - today_tmp.getTimezoneOffset()*60*1000);
let lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0).getDate();
let myDate = today;
//some other function code
For me this case was a surprise. Due this function only calling inside another function in a special circumstance. After I did a debug and this function is asking for date to be defined first.
I use gremlin-javascript (in aws Neptune) to traverse the remote graph and get a list of vertex. I want order the vertex by their createdAt date property. But since I have multiple order().by(), I want to group them by week.
const gremlin = require('gremlin')
const moment = require('moment')
const { Graph } = gremlin.structure
const { DriverRemoteConnection } = gremlin.driver
const __ = gremlin.process.statics
const { order } = gremlin.process
const getWeek = date => parseInt(moment(date).format('YYYYWW'), 10)
const graph = new Graph()
const dc = new DriverRemoteConnection(endpointNeptune)
const g = graph.traversal().withRemote(dc)
g.V().order().by(getWeek(__.values('createdAt')), order.decr)
But this throw an error: "Could not locate method: NeptuneGraphTraversal.by([202029, decr])"
Thank you in advance
Copying my earlier comment to an answer:
The by modulator is expecting a key name not a literal value. Something like
g.V().group().by('createdAt').order(local).by(keys,desc)
or perhaps depending on your data model
g.V().order().by('createdAt', order.desc)
I try to calculate a diff between hours and minutes using moment.
for example I want to calculate the diff between: 8:00 and 18:00 (should be 10:00).
But in my code it come out totalMinutes = 600. why?
const xin = '8:00';
const xout = '18:00';
const a = moment(xin, 'HH:mm');
const b = moment(xout, 'HH:mm');
const totalHours = moment.duration(b.diff(a)).asHours();
const totalMinutes = moment.duration(b.diff(a)).asMinutes();
console.log({ r: `${totalHours}:${totalMinutes}` });
// 10:600
You are trying to get diff in hours and minutes which wouldn't give the expected result as they are same thing in different unit. convert them to milisecond, wrap them in moment and format.
const moment = require("moment");
const xin = "8:00";
const xout = "18:00";
const a = moment(xin, "HH:mm");
const b = moment(xout, "HH:mm");
const duration = moment.utc(moment.duration(b.diff(a)).asMilliseconds()).format("HH:mm");
console.log(duration);
A cronjob time syntax such as "* * * * * *" followed cron npm
I want convert time from "2017-05-09T01:30:00.123Z" to cron job time format. Have library or method can implement it?
const dateToCron = (date) => {
const minutes = date.getMinutes();
const hours = date.getHours();
const days = date.getDate();
const months = date.getMonth() + 1;
const dayOfWeek = date.getDay();
return `${minutes} ${hours} ${days} ${months} ${dayOfWeek}`;
};
const dateText = '2017-05-09T01:30:00.123Z';
const date = new Date(dateText);
const cron = dateToCron(date);
console.log(cron); //30 5 9 5 2
FYI, you've mentioned "* * * * * *" as a syntax/format of cron which is incorrect. The correct format consists of 5 values separated with spaces (instead of 6 values).
I don't know if there is any library for it or not. But you can simply implement it using simple date functions.
var date=new Date("2017-05-09T01:30:00.123Z");
var mins=date.getMinutes();
//mins variable for the 1st * and so on
var secs=date.getSeconds();
var dayofmonth=date.getDate();
var month=date.getMonth();
var dayofweek=date.getDay();
You can then build a string and use those values in the cron module.
I have the following code:
var dateFormat = 'YYYY-MM-DD HH:mm:ss';
var time_margin = 10;
var last_message = moment().format(dateFormat);
var comparison = moment(last_message).add(time_margin, 'seconds').format(dateFormat);
var actualtime = moment().format(dateFormat);
var secondsDiff = actualtime.diff(comparison, 'seconds');
console.log("secondsdiff",secondsDiff);
It crashes right in var secondsDiff = actualtime.diff(comparison, 'seconds'); with Missing error handler on "socket".
TypeError: undefined is not a function.
comparison 2015-04-12 18:00:41
actualtime 2015-04-12 18:00:42
What might be wrong? I'm really not understanding
The problem is that you are trying to call diff on a string. When you call moment().format(dateFormat), what you have as result is a string, not an instance of moment.
In order to fix it, you need to call diff without formatting:
var dateFormat = 'YYYY-MM-DD HH:mm:ss';
var time_margin = 10;
var last_message = moment().format(dateFormat);
var comparison = moment(last_message).add(time_margin, 'seconds').format(dateFormat);
var secondsDiff = moment().diff(comparison, 'seconds');
console.log("secondsdiff",secondsDiff);
// => secondsdiff -9