How Can I Get Yesterdays Date With DateTime()

I’d like to get yesterdays date using DateTime, but I’m not sure how, as you cant just subtract second like with os. time.

With DateTime can’t you just subtract 1 day (D or DD) from the D or DD given, or does that cause issues with the month?

I format it as DateTime:FormatUniversalTime(“LL”, en), which prints this: July 25, 2024, but I guess I could reconstruct that with months, days and years?

But then wouldn’t there be an issue with leap years, because even if I change the month back when the day hits zero, I need to know the last day of that month?

I suppose i could store it in a datastore named Yesterday’s date and change it?

Uh, did not check if it works, but it should give you yesterday midnight

local Time = DateTime.now().UnixTimestamp
local Yesterday = os.date("!*t",86400 * math.floor(Time / 86400))

Do you know what format thats in? Such as (Month | Day , year)?

Well, this code printed for me 07/25/24: (Currently its the 7/26/24)

local Time = DateTime.now().UnixTimestamp
local Yesterday = os.date("%x",86400 * math.floor(Time / 86400))
print(Yesterday)

Does it account for months and years aswell, for say Mar 1 - Feb 29th?

What do you mean? it prints the date of yesterday

Do you have a version of this that works with only universal time, as its still the 25th for me

This should work provided UnixTimestamp is not a ReadOnly property:

local yesterdayDateTime = DateTime.now()
yesterdayDateTime.UnixTimestamp -= 86400

Then can I format datetime after ,

yesterdayDatetime:FormatUniversalTime("LL", "en")

And it should turn into the same as yesterday?

Wait, try to run this code, I did not test it but I think it should work?

local Time = DateTime.now().UnixTimestamp
local YesterdayTable = os.date("!*t",86400 * math.floor((Time) / 86400) - 1)
local Yesterday = YesterdayTable["month"].."/"..YesterdayTable["day"].."/"..YesterdayTable["year"]
print(Yesterday)

I’m not sure, and I don’t have access to Roblox Studio currently, so I can’t check.

It prints for me 7/24/24, I think it works as it uses UTC time here.

I believe it is, I get the error UnixTimstamp cannot be assigned to

Here’s an alternative solution:

local now = DateTime.now() 
local yesterday = DateTime.fromUnixTimestamp(now.UnixTimestamp - 86400)
local currentTime = os.time()
local yesterday = os.date("*t", currentTime - 86400)
local formattedDate = string.format("%04d-%02d-%02d", yesterday.year, yesterday.month, yesterday.day)
print(formattedDate)

-24 hours from the current time …

Try one of this???

DateTime.now().UnixTimestamp - 86400
os.time() - 86400
local Now = os.date("*t") 
local UnixYesterday = os.time{hour = Now.hour, min = Now.min, sec = Now.sec, year = Now.year, month = Now.month, day = Now.day - 1}

Works for me.