Check if timestamp is X seconds old in C#?

I have two unix timestamps old and new and I want to check if 30 seconds has passed between them. I want to check if oldTs is 30 seconds old or not. Basically if oldTs is <= 30 second old then I want to return true otherwise I want to return false.

long oldTs = long.Parse(processData.timestamp);
long currentTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

return currentTimestamp >= (oldTs + TimeSpan.FromSeconds(30));

I tried above code but I get an error as –

Operator '+' cannot be applied to operands of type 'long' and 'TimeSpan'

What is wrong I am doing here?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Set both variables in seconds. You have to simply to oldTS + 30.

You can get the the unix timestamp like this

long unixTimestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

Method 2

This return a TimeSpan data type.

TimeSpan.FromSeconds(30)

You can try get the milliseconds of it.

TimeSpan.FromSeconds(30).TotalMilliseconds

I hope it helps. Happy coding.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x