Get the length between two dates in hours - javascript

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

Related

Convert Javascript Date object to Filetime

Can't believe I'm unable to find the very simple case of converting a Javascript date object to Filetime.
The other way around popped up a lot while searching.
I have provided the solution below for anyone else who is looking for it.
To convert now to Filetime:
function filetimeFromDate(date) {
return date.getTime() * 1e4 + 116444736e9;
}
const now = new Date();
const filetimeNow = filetimeFromDate(now);
console.log(filetimeNow);

How to add input from a prompt to the local time using only JavaScript?

I'm a software engineering student in an Intro to JavaScript course and I'm stuck on an assignment. Here's the assignment,
in a file named alarmTime.html, use prompt() to find out how long the user wishes to nap. Then, write a statement to the document telling the user what time her/his alarm should go off. Be sure the times are local for the user.
I'm stuck on adding the input to the user's local time. I don't really know what I'm doing wrong and I'm having difficulty understanding what to do because all I'm getting is what seems to be random numbers. Please take a look at my code and point me in the right direction.
var howLong = prompt("How long, in hours, do you want to nap for?", 1);
var parsedInput = parseFloat(howLong);
var today = new Date();
var currentTime = today.toLocaleTimeString();
var myHour = today.getHours(currentTime);
var alarm = today.setHours(myHour + parsedInput);
document.write(alarm);
The reason is because of this statement document.write(alarm);. setHours method in Date object updates the Date instance, and returns the Date in milliseconds. Therefore, you are printing the Date object as the number of milliseconds since January 1, 1970. To fix that, simply replace it with document.write(today);
The problem is var alarm = today.setHours(myHour + parsedInput);
instead try to set the variable as
var alarm = today.getHours();
or change document.write(alarm); to document.write(today);
Date.now() will give you current time (users local time). Add time from prompt and your good:
let napTime = prompt('how many minutes do you want to nap?');
let alarmTime = new Date(Date.now()+napTime*60000);
//if you want to get HOURS instead of minutes
//let alarmTime = new Date(Date.now()+napTime*3600000);
//print it out. toLocale...() functions return local FORMAT of the datetime,
//they dont deal with timezones
document.write('set alarm to '+alarmTime.toLocaleTimeString('en-US'));
console.log(alarmTime);

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

Calculate a couple of business days before a date

I have to calculate X working days before a date in javascript. I have an array of holidays, how can I do this?
I can make a while loop with my date and change it to the previous day and check if it's a business day then increment my variable but is it a good way to do this?
In normal languages you could easily solve this with a hashset. It has vary fast look up times, and random access.
However, Javascript isn't like all the other children. So it has it's own special way of doing this. The easiest way is just an object.
var holidays = {
1:true,
7:true,
18:true
}
I use days since newyear, but there isn't anything wrong with using a date or something else.
Then you can make a little helper function:
var checkDate = function(value){
return holidays [value] === true;
};
Then you just do checkDate(dayOfYear) and it will return true or false if it's a holiday. Then you can easily do
//This is more pseudocode than javascript, since I haven't done javascript in years
while checkDate(--dayOfYear === true)
previousBussinesDay = dayOfYear;
Or something similar to find the actual day.

SharePoint/Javascript: comparing calendar date times in javascript

I am trying to find the best approach to comparing date/times using Javascript in order to prevent double booking on a SharePoint calendar. So I load an array with items that contain each event, including their start date/time and end date/time. I want to compare the start date/time and end date/time against the start/end date/times in the object, but I am not sure how to ensure that dates will not lapse.
like:
//date that is created from user controls
var startDate = new Date(startDat + 'T' + startHour + ':' + startMin + ':00');
var endDate = new Date(endDat+ 'T' + endHour+ ':' + endMin+ ':00');
for ( var i = 0; i < allEvents.length; i++ ) {
var thisEvent = allevents[i];
//having trouble with the compare
//i have tried silly ifs like
if (thisEvent.startDate >= startDate && thisEvent.endDate <= endDate) {
// this seems like I am going down the wrong path for sure
}
}
I then tried breaking apart the loaded object into seperate values (int) for each component of the date
var thisObj = { startMonth: returnMonth(startDate), startDay: returnDay(startDate), etc
but I am not sure this isn't just another silly approach and there is another that just makes more sense as I am just learning this.
I have a similar requirement in progress but chose to solve it at the booking stage, with jQuery/SPServices.
The code is still in build (ie not finished) but the method may help.
I attach an event handler to a column, then on selection, fetch all the dates booked in the same list to an array, then display that array on a rolling 12 month cal, as below.
I'm not checking to ensure a new booking doesn't overlap but a quick scan through the array on Pre-Save would provide a strict Go/No Go option for me. Relies on client side JS though, so not going to work in a datasheet or web services context.

Categories

Resources