Dayjs difference between two date time has a default of 8hours - javascript

I am confused why the difference between these two dates has a default of 8 hours? I am expecting a result something like 00:12:32 at least in my case from the time I posted this. Right now, in the result, the hour has a default of 8.
const date1 = dayjs(Date.now())
const date2 = dayjs(1674235010388)
// Check date date1
console.log('date1 =', dayjs(date1).format('hh:mm:ss'))
// Check date2 date
console.log('date2 =', dayjs(date2).format('hh:mm:ss'))
const result = date1.diff(date2)
console.log(dayjs(result).format('hh:mm:ss'))
<script src="https://cdn.jsdelivr.net/npm/dayjs#1/dayjs.min.js"></script>

I cannot tell you but it is another reason for not using these frameworks when plain JS is more predictible
const ms2hhmmss = ms => new Date(ms).toISOString().slice(11,19); // grab the time from YYYY-MM-DDTHH:MM:SS.milZ
const date1 = new Date()
const date2 = new Date(1674235010388)
console.log(date1)
console.log(date2)
const diff = Math.abs(date1 - date2)
console.log(ms2hhmmss(diff))

Here's how to do it with dayjs and the duration plugin, in case anyone comes here looking for that answer. For some reason I had to make the loading of the duration plugin async and wire it up manually. I expect it has something to do with a) Stack Snippets and b) the lack of caffeine in my brain.
#mplungjan is correct, of course, it's quite simple without dayjs as well.
document.querySelector('#duration').onload = (e) => {
dayjs.extend(dayjs_plugin_duration);
const date1 = dayjs(Date.now())
const date2 = dayjs(1674235010388)
// Check date date1
console.log('date1 =', date1.format('YYYY-MM-DD hh:mm:ss'))
// Check date2 date
console.log('date2 =', date2.format('YYYY-MM-DD hh:mm:ss'))
const result = dayjs.duration(date1.diff(date2));
console.log(result.format('HH:mm:ss'))
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/dayjs.min.js" integrity="sha512-hcV6DX35BKgiTiWYrJgPbu3FxS6CsCjKgmrsPRpUPkXWbvPiKxvSVSdhWX0yXcPctOI2FJ4WP6N1zH+17B/sAA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/duration.min.js" integrity="sha512-QxVJ3lAILV0RSq3wPNV5CFNyyywxd5QfA9jfGfzVViwpL/eWSi5dR1nZMc02c+QE4xz2L1eQvx/fn18RrUq9lw==" crossorigin="anonymous" referrerpolicy="no-referrer" id="duration" async></script>

Related

why IsBefore moment js gives me false when should be true

My code is this:
const nowDate = moment(new Date()).format("DD/MM/YYYY");
let paraRepDate = '01/01/2021';
let calcParaDate = '30/06/2021';
var x = moment(calcParaDate).isBefore(nowDate)
console.log(x) // false
How is it possible?
Default format of momentjs is MM/DD/YYYY. In your solution you can see warning information in console:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Solution
You have to specify format moment(date, format). Something like this:
const format = 'DD/MM/YYYY';
const nowDate = moment();
const calcParaDate = '30/06/2021';
const isBefore = moment(calcParaDate, format).isBefore(nowDate)
console.log(isBefore);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js" integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Also you don't have to pass new Date() in moment() for current datetime.

Construct Moment JS format same as new Date() format [duplicate]

I have a date object that I want to
remove the miliseconds/or set to 0
remove the seconds/or set to 0
Convert to ISO string
For example:
var date = new Date();
//Wed Mar 02 2016 16:54:13 GMT-0500 (EST)
var stringDate = moment(date).toISOString();
//2016-03-02T21:54:13.537Z
But what I really want in the end is
stringDate = '2016-03-02T21:54:00.000Z'
There is no need for a library, simply set the seconds and milliseconds to zero and use the built–in toISOString method:
var d = new Date();
d.setSeconds(0,0);
document.write(d.toISOString());
Note: toISOString is not supported by IE 8 and lower, there is a pollyfil on MDN.
While this is easily solvable with plain JavaScript (see RobG's answer), I wanted to show you the Moment.js solution since you tagged your questions as "momentjs":
moment().seconds(0).milliseconds(0).toISOString();
This gives you the current datetime, without seconds or milliseconds.
Working example: http://jsbin.com/bemalapuyi/edit?html,js,output
From the docs: http://momentjs.com/docs/#/get-set/
A non-library regex to do this:
new Date().toISOString().replace(/.\d+Z$/g, "Z");
This would simply trim down the unnecessary part. Rounding isn't expected with this.
A bit late here but now you can:
var date = new Date();
this obj has:
date.setMilliseconds(0);
and
date.setSeconds(0);
then call toISOString() as you do and you will be fine.
No moment or others deps.
Pure javascript solutions to trim off seconds and milliseconds (that is remove, not just set to 0). JSPerf says the second funcion is faster.
function getISOStringWithoutSecsAndMillisecs1(date) {
const dateAndTime = date.toISOString().split('T')
const time = dateAndTime[1].split(':')
return dateAndTime[0]+'T'+time[0]+':'+time[1]
}
console.log(getISOStringWithoutSecsAndMillisecs1(new Date()))
function getISOStringWithoutSecsAndMillisecs2(date) {
const dStr = date.toISOString()
return dStr.substring(0, dStr.indexOf(':', dStr.indexOf(':')+1))
}
console.log(getISOStringWithoutSecsAndMillisecs2(new Date()))
This version works for me (without using an external library):
var now = new Date();
now.setSeconds(0, 0);
var stamp = now.toISOString().replace(/T/, " ").replace(/:00.000Z/, "");
produces strings like
2020-07-25 17:45
If you want local time instead, use this variant:
var now = new Date();
now.setSeconds(0, 0);
var isoNow = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
var stamp = isoNow.replace(/T/, " ").replace(/:00.000Z/, "");
Luxon could be your friend
You could set the milliseconds to 0 and then suppress the milliseconds using suppressMilliseconds with Luxon.
DateTime.now().toUTC().set({ millisecond: 0 }).toISO({
suppressMilliseconds: true,
includeOffset: true,
format: 'extended',
}),
leads to e.g.
2022-05-06T14:17:26Z
You can use the startOf() method within moment.js to achieve what you want.
Here's an example:
var date = new Date();
var stringDateFull = moment(date).toISOString();
var stringDateMinuteStart = moment(date).startOf("minute").toISOString();
$("#fullDate").text(stringDateFull);
$("#startOfMinute").text(stringDateMinuteStart);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.js"></script>
<p>Full date: <span id="fullDate"></span></p>
<p>Date with cleared out seconds: <span id="startOfMinute"></span></p>
let date = new Date();
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
I hope this works!!
To remove the seconds and milliseconds values this works for me:
const date = moment()
// Remove milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm:ss[Z]'))
// Remove seconds and milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm[Z]'))
We can do it using plain JS aswell but working with libraries will help you if you are working with more functionalities/checks.
You can use the moment npm module and remove the milliseconds using the split Fn.
const moment = require('moment')
const currentDate = `${moment().toISOString().split('.')[0]}Z`;
console.log(currentDate)
Refer working example here:
https://repl.it/repls/UnfinishedNormalBlock
In case for no luck just try this code
It is commonly used format in datetime in the SQL and PHP
e.g.
2022-12-25 19:13:55
console.log(new Date().toISOString().replace(/^([^T]+)T([^\.]+)(.+)/, "$1 $2") )

How can I get the ISO format for date and time in javascript?

I have two separate fields of date and time:-
const date = 2020-12-10;
const time = 22:00;
expected output:-
2020-12-10T10:00:00Z
I'm following this approach but the time in coming wrong:-
const date = DateUtil.getFullDateString(this.state.date_value);
const time = moment(this.state.time_value, ['HH.mm']).format('hh:mm a');
const momentObj = moment(date + time, 'YYYY-MM-DD HH:mm');
const dateTime = momentObj.toISOString();
the output of time is coming 18:30:00 but need to have 10:00:00
2020-12-10T18:30:00Z
You could parse date and time one by one, then add time to date and finally format as you want.
const date = '2020-12-10';
const time = '22:00';
const momentDate = moment(date).utc().startOf('day'); // utc() to avoid the offset
console.log(momentDate);
const momentTime = moment(time, 'HHmm').format('HH:mm');
console.log(momentTime);
const resultTime = momentDate.add(momentTime);
console.log(resultTime);
// Format as you want
console.log(resultTime.format('LLL'));
console.log(resultTime.format('YYYY-MM-DDThh:mm:ss.SSSA[Z]'));
console.log(resultTime.toISOString());
<script src="https://momentjs.com/downloads/moment.js"></script>
See this in order to know how to manage the UTC offset.

Moment Timezone not returning expected result

I might be doing something silly here. But essentially, the time in Lisbon right now is 12:27 PM
but the following returns 14:27 (EU central time)
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment.tz(item.startTime, format, timeZone);
const endMoment = moment(item.endTime, format, timeZone);
return time.isBetween(startMoment, endMoment);
I tried several combinations and I get the wrong answer everytime. For example if I set timeZone to be "Europe/Warsaw" it returns 15:27 whereas it should be 13:27.
EDIT: const currentTime = moment().tz("Europe/London").format() returns the correct time for London. However, the return statement moment(currentTime).isBetween(startMoment, endMoment) still reads "moment(correntTime)" as the local time.
isBetween return boolean . And isBetween runs on date object. You are trying to run on time zone object. which is different from date object
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment().subtract(8, 'months').tz(timeZone).format();
const endMoment = moment(new Date()).tz(timeZone).format() ;
console.log("startMoment",startMoment)
console.log("endMoment",endMoment)
console.log(moment.tz(new Date(),"Europe/Lisbon").format())
console.log(moment('2020-09-30').isBetween(startMoment, endMoment));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

Get timezone specific date using momentjs

I am trying to calculate the time difference between two dates using moment-timezones but every time it it showing the same difference.
I am calculating the time like this:
const end_time = moment.tz(end_date, timezone);
const current_time = moment.tz(moment.tz.guess());
const difference = end_time - current_time;
let duration = moment.duration(difference, 'milliseconds');
I am getting the same duration no matter what timezone I set.
Can anybody suggest me how to get the correct difference using moment?
Use diff method, to check the duration differences between two objects
var now = moment.tz("2020-05-14 00:00:00", "Europe/Berlin");
var end = moment.tz("2016-05-14 00:00:00", "Europe/Berlin");
var diff = now.diff(end);
console.log("diff is: " + diff);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>

Categories