Storing the time and the Data in firebase Database - javascript

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

Related

How to get local time date instead UTC time in Node.js?

I want to get variable to save image name format using the date.
I use this following code.
const time = new Date().toJSON().slice(0,10).replace(/-/g, '');
My expected variable is 20220629. Because my local time is June 29, 2022.
But, the result variable is 20220628. I think this result time using UTC time.
Update:
I try to using JS method like toLocalDateString() and get local time.
const time = new Date().toLocaleDateString().replaceAll('/', '');
But the result is 29062022 not 20220629.
Can anyone help me how to convert into localtime? Thank you.
The date functions rely a lot on system settings to get your local date and time. If you're in the U.S. that happens to be month/day/year.
You simply need to deconstruct it to get what you're looking for. The below code will get it in the order you're looking for (and account for the month being 0-indexed):
const time = new Date()
const time2 = '' + time.getFullYear() + (time.getMonth() + 1) + time.getDate().toString().padStart(2,'0')
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

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

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);

Failing to increment date with moment.js

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>

Compare Server Time and Browser Time

My table that has 3 columns: FileName, LastUpdateTime, and a Restart button.
I need to display the restart button only if the last update time is more than 20 min ago. I get the last update time from the server. d = new Date() gives the local browser time but the lastUpdateTime is coming from the server. Server is in the different time zone than the clients browser.
The following code works if both server and browser are in the same time zone. Do you have any suggestions on how solve this if the server and browser are in a different time zone?
This application supposed to run anywhere in US and Europe.
var lastUpdatedTime = (gridData[i].LastTimeUpdated);
var d = new Date();
//deducting 20 min from current time
var deductTwenty = d.setMinutes(d.getMinutes() - 20);
var parsedupdatetime = Date.parse(lastUpdatedTime);
// If the last update time is not 20 ago, hide it.
if (parsedupdatetime > deductTwenty) {
newrestartButton.hide();
}
Use .NET in your .cshtml file to get the date server-side. Assuming you use MVC (since you tagged this question kendo-asp.net-mvc).
#{
var deductTwenty = DateTime.Now.AddMinutes(-20);
}
<script>
var jsDeductTwenty = new Date(#deductTwenty.Year, #deductTwenty.Month-1, #deductTwenty.Day, #deductTwenty.Hour, #deductTwenty.Minute);
</script>
Result:
What's probably going wrong is the server date parsing. Take a look at the Date.parse function spec - and make sure your server is returning something that will get parsed correctly like an ISO8601 formatted date.
You have to convert your lastUpdatedTime with client timezone, means you should convert server time to client time when subtracting date with 20 mins. You can use momentjs, moment-timezone and jstimezonedetect to achieve this.
Your code should be like this
// get current client timezone with jstimezonedetect
var currentTz = jstz.determine().name(); // e.g "Europe/London"
// parse last update time to moment object and change its timezone
var lastUpdateTime = moment(lastUpdatedTime, "M/DD/YYYY hh:mm a").tz(currentTz);
// create date using moment and deduct 20 mins from it
var deductTwenty = moment().subtract(20, 'minutes');
// now compare
if (lastUpdateTime > deductTwenty) {
newrestartButton.hide();
}
Hope this help.

Categories

Resources