Convert Javascript Date object to Filetime - javascript

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

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

Cypress API testing - Using custom commands to return a value to avoid duplicating code

First of all. I'm purposely re-learning JS/Cypress and I'm purposely starting from bedrock again, so apologies in advance.
I'm currently using Cypress for REST API testing. I am migrating tests over from an existing Ruby/Selenium framework and I want to use something similar to writing Ruby functions to clean up my code, as I am currently duplicating code.
An example:
I have a block of code that generates a date, 365 days in the past (ISOString used for a reason, in this case)
var date = new Date();
date.setDate(date.getDate() - 365)
var minDate = date.toISOString().split('T')[0]
I want to do something like
Cypress.Command.add('dateGen', () => {
var date = new Date();
date.setDate(date.getDate() - 365)
var minDate = date.toISOString().split('T')[0]
})
and call it in. In this case, I would want to call it in to my test using something like
(excuse the incorrect syntax, I'm just doing it as a like for like (Ruby/JS) illustration):
var date = cy.dateGen
However, running this in any js/cypress friendly combination falls over as Commands do not return values.
I am already set up to use commands in index.js etc, so that bit isn't causing me any problems. I am already using commands for things that don't return a value, so I know I'm doing that bit correctly.
I sorted it using the following:
Cypress.Commands.add('dateGenerator', (days) => {
var newDate = new Date();
newDate.setDate(newDate.getDate() - days)
var date = newDate.toISOString().split('T')[0]
return date
})
and then called it via
cy.dateGenerator(noOfDays)
.then((date) => {
var minDate = date
}
The bit I was missing was the
return date and I was closing the blocks off too early in my test code.

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

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

Strange javascript assignment

I've worked with C# for many years but I'm pretty inexperienced when it comes to javascript so this should be an easy pick for any of you javascript wizards. I was looking through a JQuery plugin for managing cookies (https://github.com/carhartl/jquery-cookie) when I saw these two lines:
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
I just want to make sure I understand this correctly; is this the equivalent of:
var days = options.expires;
options.expires = new Date();
var t = options.expires;
t.setDate(t.getDate() + days);
I imagine this is an attempt to compress the code as much as possible but I admit I get confused when thinking about what the value of the variables are. Especially since options.expires can be either a javascript date object or a number of days.
Yes. The return value of an assignment is the value that was assigned.

Categories

Resources