Failing to increment date with moment.js - javascript

Well, I just can't increment a date with moment.js. I get a javascript date object in my code, wrap it into moment function, calculate the amount of hours I need to add to the initial date and after I use .add method nothing happens. Tried doing something like currentTime.add(2, 'hours'), that didn't work as well. What am I doing incorrectly?
const currentTime = moment(ioc.get<Main.IArchiveManager>("ArchiveManager").getCurrentDate());
const speed = this.getData().speed;
const distance = this.calcDistanceFromPrevPoint(initialPoint,prevPoint);
const timeToReachPoint = (distance / speed) * 60;
const estimatedTime = currentTime.add(timeToReachPoint, 'hours');
debugger;
return estimatedTime;
this is a screenshot from my devtool so you know what is going on:

Everything is working as expected. You are logging the value of currentTime after it got changed. Remember that .add() changes the value of the object, it does not return a copy, but the object itself (for better chaining). See my example, you'll see that the came console.log, called twice but at different timings displays the values you'd expect.
var time = moment(new Date());
console.log(time);
time.add(2,'h');
console.log(time)
<script src="https://momentjs.com/downloads/moment.min.js"></script>

You have to use format() (or .toString() or .toISOString()) to display the value of a moment object.
Note that:
moment objects are mutable, so calling add will change the original object, if you need you can use the clone() method
Do not use Internal properties (prefixed with _)
Your code is fine, you are just logging moment object the wrong way:
const currentTime = moment();
console.log(currentTime.format())
const speed = 0.1//this.getData().speed;
const distance = 20.56;// this.calcDistanceFromPrevPoint(initialPoint,prevPoint);
const timeToReachPoint = (distance / speed) * 60;
const estimatedTime = currentTime.add(timeToReachPoint, 'hours');
console.log(estimatedTime.format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Related

Get the length between two dates in hours

I am reading sleep data into my react-native app using react-native-healthkit, and I need to find a way to get the total amount of sleep time. The data is read in like this:
If anyone has any ideas on the best way to handle this data, please let me know.
extension Date {
/// Hours since current date to given date
/// - Parameter date: the date
func hours(since date: Date) -> Int {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.hour], from: self, to: date)
return dateComponents.month ?? 0
}
}
date2.hours(since: date1)
Using .timeIntervalSince is a bad practice, because some hours may be shorter than other.
If anyone has any ideas on the best way to handle this data please let me know.
It really depends on how you're parsing that JSON data. I won't cover JSON parsing here because there are many, many tutorials and blog posts on that topic. Here's one in case you're not sure where to start.
Your goal is to end up with date objects (Date in Swift, NSDate in Objective-C). For example, if you have the values as strings, you can use DateFormatter to parse the strings into Date objects.
Once you have those date objects you can use the operations that those objects supply to get a TimeInterval, which is a double representing an interval in seconds. Convert that to hours by dividing by 3600:
let interval = endDate.timeIntervalSince(startDate)
let hours = interval / 3600
Try this
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
guard let startDate = dateFormatter.date(from: "yourStartDate"),
let endDate = dateFormatter.date(from: "yourEndDate") else {
return
}
let difference = endDate.timeIntervalSince(startDate)
If you are targeting iOS 13 and above you can use
endDate.hours(since: startDate)
instead of timeInterval

update fullCalendar( ‘getDate’ ) regularly

I need to update a moment variable like
var moment = calendar.fullCalendar('getDate');
regularly by using setInterval function but that doesn't have any effect and the moment variable is always the same. Is there a method to have the current moment updated each X seconds ?
thanks,
Perhaps I've misunderstood, but it's not really clear why you want to use fullCalendar's getDate function. This will return the date currently selected in fullCalendar. Updating that every few seconds wouldn't be much use - it'll only change whenever the user selects a new date.
If you want to report the actual current time, you can do it easily using momentJS directly, something like this:
var m;
function currentTime() {
m = moment();
console.log(m.toISOString());
}
setInterval(currentTime, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Storing the time and the Data in firebase Database

Im trying to create a JavaScript function that is storing some information in firebase Database each time it is called. One information that I want to store is the current Date and Time that the function has been called. I’ve create something on my own but the formation of the date and time isn’t quite how I want it to be. My source code of the function is the following:
function AddtoDatabase(id,title,description){
var rootRef = firebase.database().ref().child(`notifications/${id}`);
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
rootRef.push({
title:`${title}`,
description:`${description}`,
//time:`${new Date().toISOString().split('T')[0]}`
time:`${(new Date(Date.now() - tzoffset)).toISOString().slice(0, -1)}`
});
}
Using the source code above i get the following result from date and time:
How can I edit the code to get just
Received at:2018-03-14 09:48
Can anyone please help me?
I think that you can achieve this simply using the Date() object's native methods like getFullYear(), getFullMonth() etc.
Here's the code.
const date = new Date();
const year = date.getFullYear();
const month = date.getFullMonth() + 1 // months start from 0
const day = date.getDay()
const hour = date.getHours();
const minutes = date.getMinutes();
const time = `Received at ${year}-${month}-${day} ${hour}:${minutes}`;
You should use the moment library for the formatting: https://momentjs.com/
In particular, look at this part of the documentation: https://momentjs.com/docs/#/displaying/
So in your case you would do:
moment().format("YYYY-MM-DD hh:mm");
Also, a best practice is to store in your database the number of milliseconds since 1970/01/01, which you can obtain through the JavaScript getTime() method

How to get the time span between two date picker values in Javascript?

I've added two Bootstrap Datetime pickers to a HTML5 form. So far I can capture the DateTime value of each picker using the change event of the control.
Now I have a case where the time span difference between both DateTime pickers needs to be stored as a var.
I did come across an example similar to this ask here. But my short implementation below alerts a value of "Nan" instead of the expected time span difference when the actual time picker value is changed.
Question:
How can you calculate the time span between two date picker values in Javascript or JQuery?
Code gist:
var start;
var actual;
$("#OutageStartDisplay").on("dp.change", function (e) {
start = $('#OutageStart').val(moment(e.date).format());
});
//On change of the ActualDisplay datetime picker
//update's the Actual hidden field with the datetime.
$("#ActualDisplay").on("dp.change", function (e) {
actual = $('#Actual').val(moment(e.date).format());
//If the actual is set, calculate the outage duration
var timeDiff = Math.abs(start - actual);
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
});
Since you're using moment, you can use moment.diff to get the time difference.
Your code also seems a bit bugged, when you do $("whatever").val(something), you're setting "whatever"s value to something and it returns $("whatever"), not the value. So you're trying to subtract a JQuery object from another JQuery object. But even if it returned the val, your val is a string - which you also cannot substract.
So you probably want this instead:
var start;
var actual;
$("#OutageStartDisplay").on("dp.change", function (e) {
start = moment(e.date);
$('#OutageStart').val(start.format());
});
$("#ActualDisplay").on("dp.change", function (e) {
actual = moment(e.date);
$('#Actual').val(actual.format());
//If the actual is set, calculate the outage duration
alert(actual.diff(start));
});

How to react to two date objects in a user's profile in Meteor

In my app users have a start and end attribute in their profile (both date objects, a few hours apart). I'd like to make my app react to these values--for example, display something if the current time is between the two times, or within 15 minutes of the start time. I have a feeling I'd want to use the Tracker.autorun piece of Meteor, I'm not sure how to use it since you don't ever manually change the time, it's something that's always changing.
something like this:
timeDif : function() {
Tracker.autorun(function() {
var m1 = moment();
var m2 = moment(Meteor.user().profile.time);
var difMin = m1.diff(m2, 'minutes');
if(difMin > 10) {foo;}
else {bar;}
})
}
As you found, that won't work because Date objects are not reactive. Have a look at something like the chronos pacakge, which provides a variety of helpers for reactive dates. Based on the docs, it looks like something like this could work:
timeDiff : function() {
var m1 = Chronos.liveMoment();
var m2 = moment(Meteor.user().profile.time);
var minutes = m1.diff(m2, 'minutes');
...
}
I'm assuming that timeDiff is a helper so you don't need the autorun. If not, let me know and I'd give some other ideas.

Categories

Resources