Cloud Firestore How to subtract hour from Timestamp - javascript

I am able to get the timestamp using this line in my index.js.
var now = admin.firestore.Timestamp.now();
I just want the timestamp that's 1 hour before now.
I've tried this and hasn't worked.
var old = now(now.seconds-1*60*60,milliseconds);
Also tried but it returns just the seconds instead of a timestamp
var old = admin.firestore.Timestamp.now().seconds - 1*60*60;
Any ideas on how to get the timestamp of an hour before?

Firestore's Timestamp class doesn't offer the ability to do "date math". You should do any date math using a native date type for your language, then convert that to a Timestamp when you're done.
Since you tagged this JavaScript, you could use a normal Date object to do the math:
const date = new Date(Date.now() - 60*60*1000)
The convert that to a Timestamp with Timestamp.fromDate():
const timestamp = admin.firestore.Timestamp.fromDate(date)

Related

Check if it's 'today' in another timezone

Given any UNIX timestamp, either created just minutes ago or multiple hours, how would I check if that UNIX falls on today's date in x timezone.
For example, I get a UNIX timestamp from a database, how would I check if that's today in say EST time?
I've tried changing timezone's with UNIX but I couldn't figure out how only with a Date object but I think there'd be an easier way than changing UNIX to a Date object then checking them against each other then changing to UNIX again.
Removing the difference in time from the UNIX timestamp then checking if it's today's date, although I think this would work I haven't yet figured out how I would write out the logic to this.
I'd really appreciate any help or explanation!
- Timjime
Get the unix timestamp for the start and end of "today", then check to see if the provided timestamp is between them.
let todayStart = new Date()
todayStart.setHours(0,0,0,0)
const todayEnd = new Date()
todayEnd.setHours(0,0,0,0)
todayEnd.setDate(todayEnd.getDate()+1)
const todayStartUnix = Math.floor(todayStart / 1000)
const todayEndUnix = Math.floor(todayEnd / 1000)
let unixTest = 12345678
console.log(unixTest > todayStartUnix && unixTest < todayEndUnix)
unixTest = Date.now() / 1000
console.log(unixTest > todayStartUnix && unixTest < todayEndUnix)

How to add time to a date in js

I get a date with string type from API and then I parse it to a date type so that I can use it for a count down.
I want to add 30 days to the date that I've got from API.
Here is the code that I parsed
const time = Date.parse("2020-12-30T18:35:43");
I've already read this question and I tried to implement it
Add 10 seconds to a Date
but react does not recognize the getDate
if you need more information, please let me know
You need to wrap your parsed date with a new Date()
const time = new Date(Date.parse("2020-12-30T18:35:43"));
// As mention by other comments, this is enough
// const time = new Date("2020-12-30T18:35:43");
time.setSeconds(time.getSeconds() + 10) // 1609349753000
setSeconds and getSeconds are method of the Date, you was trying to execute them on a number.
EDIT :
Answer can be found here
In a general way you should use date-fns for date manipulations ;)
you can also setDate to your existing date. Check following code.
const date = new Date("2020-12-30T18:35:43");
date.setDate(date.getDate() + 30);

How to convert a string eg: '8/31/2020' to a date, and substract it from todays date to find number of days that have passed in JavaScript

In my MVC project, I am trying to get the start date value from a cookie which returns a string m/dd/yyyy and I am trying to figure out how to find the number of days that have passed from the string date until now in JavaScript so the function occurs on the client side in the view.
My javascript is incredibly rusty.
currently my cookie value returns string '8/31/2020'. How can I convert this to a javascript date and find how many days have passed?
Any help will be greatly appreciated!
Considering that cookieDate is always in the past, this is the shortest answer:
const cookieDate = new Date('8/31/2020'); const today = new Date();
const diffDays = Math.ceil((today - cookieDate)/(1000*60*60*24)); // diffDays = 22
If you care about daylight saving time check this answer.

Use moment.js to change the timezone on a datetime stamp, without changing the time

I am migrating event data from an old SQL database to a new Mongo database, using NodeJS. However, whoever set up the SQL database created all of the dates for the events, made the times in PST/PDT, but the database believes they are in UTC time.
For Example:
A date from the SQL database may be: 23-APR-10 which MomentJS shows as: 2010-04-23T21:00:00Z when 21:00:00 is the PST time.
Is it possible to use pure JavaScript/MomentJS/NodeJS or a different npm module to change the timezone on the DateTime string without modifying the time (i.e. 2010-04-23T21:00:00Z would become 2010-04-23T21:00:00-8:00)?
PS. Even though the SQL database only shows DD-MMM-YY but returns a DateTime string when I query it.
Following the line of inquiry in the question comments, it seems your problem is that due to the timezone mishap, the timestamps stored in the db are stored without the timezone offset, and since your desired timezone is PST (UTC-8hours), the timestamps are 8 hours ahead, for instance, what should have been 2010-04-23T13:00:00Z has become 2010-04-23T21:00:00Z.
So what needs to be done here is that the utc offset for your desired timezone needs to be obtained and added to the date.
The offset in your case is known (-8 hours). However, we can fetch the correct offset of any desired timezone from the moment-timezone library.
const moment_timezone = require('moment-timezone');
//a sample timestamp you're getting from your db
const myDateObj = new Date("2010-04-23T21:00:00Z");
//timezone for PST as understood by moment-timezone
const myMomentTimezone = "America/Los_Angeles";
//offset for your timezone in milliseconds
const myTimezoneOffset = moment_timezone.tz(myMomentTimezone).utcOffset()*60000;
//perfom the correction
const getCorrectedDateObj = (givenDateObj) => new Date(givenDateObj.valueOf() + myTimezoneOffset);
console.log(getCorrectedDateObj(myDateObj));
You may notice that we are actually changing the timestamp, because the given timestamp and the requried timestamp are, due to the nature of the error, essentially different timestamps. Moment-timezone is only being used here to fetch the offset, it's not used to "convert" anything.
Anuj Pancholi's answer is correct, however; the old SQL database I'm using seems to have a lot of quirks, so I had to modify his answer to get my code working.
My Solution:
function getCorrectedDateObj(myDateObj){
const timezoneOffset = momentTimeZone.tz(timezone).utcOffset() * 60000;
const dt = new Date(myDateObj.valueOf() + timezoneOffset / 2);
dt.setHours(dt.getHours() + 12);
}

Get current timestamp in NodeJS in DD-MM-YY-23:59:42 format

I am running NodeJS 8 in AWS Lambda and want to timestamp and attach to an S3 the current day, month, year and current time when the function runs.
So if my function was running now, it would output 220619-183923 (Todays date and 6.39pm and 23 seconds in the evening.)
For something a little complex like this do I need something like MomentJS or can this be done in pure Javascript?
Eventually this will make up a S3 URL such as
https://s3.eu-west-2.amazonaws.com/mybucket.co.uk/BN-220619-183923.pdf
UPDATE
The webhook appears to have some date/time data albeit in slightly different formats that weren't outputted in the Lambda function, so these could prove useful here. Can ':' be used in a URL and could the UTC which I assume is in milliseconds be converted into my desired format?
createdDatetime=2019-06-22T18%3A20%3A42%2B00%3A00&
date=1561231242&
date_utc=1561227642&
Strangely, the date_utc value which is actually live real data. Seems to come out as 1970 here?! https://currentmillis.com/
You don't need moment. I have included a solution that is quite verbose, but is understandable. This could be shorted if needed.
Since you are using S3, you might also consider using the UTC versions of each date function (ie. .getMonth() becomes .getUTCMonth())
Adjust as needed:
createdDatetime= new Date(decodeURIComponent('2019-06-22T18%3A20%3A42%2B00%3A00'))
date=new Date(1561231242 * 1000);
date_utc=new Date(1561227642 * 1000);
console.log(createdDatetime, date, date_utc)
const theDate = createdDatetime;
const day = theDate.getUTCDate();
const month = theDate.getUTCMonth()+1;
const twoDigitMonth = month<10? "0" + month: month;
const twoDigitYear = theDate.getUTCFullYear().toString().substr(2)
const hours = theDate.getUTCHours();
const mins = theDate.getUTCMinutes();
const seconds = theDate.getUTCSeconds();
const formattedDate = `${day}${twoDigitMonth}${twoDigitYear}-${hours}${mins}${seconds}`;
console.log(formattedDate);
UPDATE based upon your update: The code here works as long as the input is a JavaScript Date object. The query parameters you provided can all be used to create the Date object.
You can definitely use MomentJS to achieve this. If you want to avoid using a large package, I use this utility function to get a readable format, see if it helps
https://gist.github.com/tstreamDOTh/b8b741853cc549f83e72572886f84479
What is the goal of creating this date string? If you just need it as a human-readable timestamp, running this would be enough:
new Date().toISOString()
That gives you the UTC time on the server. If you need the time to always be in a particular time zone, you can use moment.

Categories

Resources