0

Hello I have a timestamp that is currently structured as a string as so "December 18, 2022 at 5:34:06 PM UTC" I am trying to get the day out of this String and structure it to a Date formate. I want to do this so I can use the Calendar.current.isDateInYesterday() function. When I try this as so

Calendar.current.isDateInYesterday(timestamp.formatted(.dateTime.day()))

I get the error "Cannot convert value of type 'Date.FormatStyle.FormatOutput' (aka 'String') to expected argument type 'Date'"

I think I cant plug in a String into this function but rather an argument with date structure. Can anyone help

burnsi
  • 6,194
  • 13
  • 17
  • 27
ahmed
  • 341
  • 2
  • 9
  • incomplete information lead to negative vote. what is timestamp? provide full code – Zeeshan Ahmad II Dec 20 '22 at 04:14
  • @ZeeshanAhmadII timestamp is December 18, 2022 at 5:34:06 PM UTC, I added this string in the description – ahmed Dec 20 '22 at 04:15
  • you just have to give Date in argument not this -> timestamp.formatted(.dateTime.day()) -> which contains error. first convert it to date then check if the date is not null the use date in argument – Zeeshan Ahmad II Dec 20 '22 at 05:41

1 Answers1

0

Assuming your date input is December 18, 2022 at 5:34:06 PM UTC, try the following to get a date object

let dateString = "December 18, 2022 at 5:34:06 PM UTC"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM dd, yyyy 'at' h:mm:ss a z"
let date = dateFormatter.date(from:dateString)! // this will crash if date is not parseable

Then you can use the date object in your check

Calendar.current.isDateInYesterday(date)
Suyash Medhavi
  • 1,135
  • 6
  • 18
  • 1
    There's no need to remove literal `at`. Use this date format `"MMMM dd, yyyy 'at' h:mm:ss a z"`. And it's highly recommended to specify the `en_US_POSIX` locale for fixed date formats. – vadian Dec 20 '22 at 07:39
  • Thanks @vadian I have updated the answer based on your suggestions – Suyash Medhavi Dec 20 '22 at 10:26