✅ How to sum datetimeoffset and timespan?
I have following structure:
I would like to get expiration time by sum timestamp and ttl
I tried this:
but it's not correct
18 Replies
uhm
you're using
DateTime.Now
in that example
also why are you mixing datetimeoffset with datetime?
this works finebut I don't think that ExpiresAt should be DateTimeOffset, it should be local time
could turn this into
DateTime
if you don't want the offset shownthe logic is following
I get the dto with timestamp, then I add it to the database
Once per hour (for example) I make a request to get all the objects that are already expired, and then I delete them
The check takes place locally, so I don't need time zones
But the timestamp is offset?
ie, if you fetch an item from me, it'll be in my timezone, so +0200
it has a 3 hour ttl
that means you need to take the offset into account when calculating the expire time, or convert it at the time of saving into database
its FAR easier to just always use offsets
let's say that this is values that I get from dto
I should add this to database and remove after "04/10/2023 7:23:57 PM -07:00" + "1.02:30:15"
So all I need is just
04/10/2023 7:23:57 PM -07:00.LocalDateTime.Add(1.02:30:15)
?dont do the whole local conversion
just keep it offset
you want the object to live
1.02:30:15
after the timestamp, right?yes
then you NEED to respect the offset
it doesnt matter what local timezone the server is in
ah
and checking the time will be look like this:
DateTime.Now > ExpiresAt - ExpiresAt.Offset
idk
use
DateTimeOffset
its literally just DateTimeOffset.Now > ExpiresAt
offset is taken into account automatically
here is an example
im in timezone 0200. Im creating a DTO that was created in 0500, and has a 3 hour time to live
that means it should expire right away when I check it, because it was created exactly 3 hours ago
lets spice it up a bit. lets make it have a 10 hour time to live
or 5 actually
so we see that when I start checking, it only has 2 hours left to live. That checks out, since it was created at 12:25 local time in +0500hm I get the idea of how to get expired objects from db (we use
DateTimeOffset.Now > ExpiresAt
)yes
and to get ExpiresAt from datetimeoffset and timespan we just do sum(datetimeoffset , timespan)
yes, thanks for helping me!
np
now I understand