Convert unix timestamp with milliseconds into postgres-readable timestamptz - javascript

Is there simple way to convert a date formatted like this: 1471866155422 into date formatted like this: 2016-08-24 15:23:31.949284+03.
I need this, because i have unix timestamps in client-side js app, and i need to implement pagination with PostgreSQL database based on timestamptz.
I assume this is good solution for pagination based on this question: Postgres: using timestamps for pagination

This works for my Chrome in Holland. Not sure if the toString() does the same for you
function pad(num) {
return String("0"+num).slice(-2);
}
function toPost(ts) {
var d = new Date(ts);
var time = d.toString().split(d.getFullYear()+" ")[1].split("(")[0].slice(0,-3)
time = time.replace(/ GMT/,"."+d.getMilliseconds())
return d.getFullYear()+"-"+pad(d.getMonth()+1)+"-"+pad(d.getDate())+" "+time;
}
alert(toPost(new Date().getTime())+"\n"+toPost(1471866155422)+"\n"+"2016-08-24 15:23:31.949284+03");

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

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

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.

Javascript Date decorator for accurate client side time

I'm currently working on some Javascript to synchronize the client side clock with our servers. I'm doing this by looking at the 'Date' header of any Ajax responses (it only has to be accurate to a few seconds).
To make the rest of the code work seamlessly with this Date function I want to override the native Date function in a decorator style so I can just enhance it with the calculated clock skew.
So far I have this (which seems to work):
var SystemDate = Date;
var ServerDate = function() {
var a = arguments;
switch(a.length){
case 0:
var system_date = new SystemDate();
return new SystemDate(system_date - ServerDate.skew);
case 1:
return new SystemDate(a[0]);
case 7:
return new SystemDate(a[0],a[1],a[2],a[3],a[4],a[5],a[6]);
}
};
ServerDate.parse = Date.parse;
ServerDate.UTC = Date.UTC;
ServerDate.skew = 0;
var Date = ServerDate;
Now whenever I get an Ajax respose I can adjust the skew property and all new instances of Date will have the adjusted value.
I'm really inviting criticism. There are a few things I'm not sure on:
Is this a good idea? - I'm not a Javascript programmer so I've no idea what sins I have just commited
How can I handle the different argument lengths more neatly - it seems very hacky
Copying the class methods UTC and parse seems very brittle
The new Date function now returns a date object on the console rather than the string representation.

Categories

Resources