Using DateFormatter for shortening the date (UNIX timestamp)

95 Views Asked by At

I am trying to solve my issue with a Unix Timestamp. I figured out how to present it but the result is too long - it says:

"Friday March 31, 2023 at 11:13:52 PM Central European Summer Time"

How can I get it shorter with a UTC time ?

something like: "31.03.2023 11:13:52 UTC"

struct effSummary: View {

    let unixvar = "1680297232"
    
    var body: some View {
        
      
        let date =      NSDate(timeIntervalSince1970:TimeInterval(unixvar)!)
            Text("\(date)")
  
     
    } }

struct effSummary_Previews: PreviewProvider {
    static var previews: some View {
        effSummary()
            .previewInterfaceOrientation(.landscapeLeft)
    } }
1

There are 1 best solutions below

2
Duncan C On BEST ANSWER

Don't use NSDate. The Swift native type is Date. And you can use the DateFormatter class method localizedString(from:dateStyle:timeStyle:) to generate formatted date strings in the user's local time zone

let date = Date(timeIntervalSince1970:TimeInterval(unixvar)!)
let dateString = DateFormatter.localizedString(
    from: date
    dateStyle: .medium
    timeStyle: .medium)
Text("\(dateString)")

Select the date and time styles .short, .medium, or .long depending on your needs. If you want more control then that you'll probably need to create a custom instance of DateFormatter and configure it the way you want it.

If you want your date string to use UTC, but not the default formatter you get from just converting it to a String, you'll need to use a DateFormatter. Code like this will work:

let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime

print(formatter.string(from: Date()))

That will output a date like

2023-04-01T17:04:17Z

Based on the example you gave:

"31.03.2023 11:13:52 UTC"

I assume that's month.day.year hour:minute:second timezone. You could get that format like this:

let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "dd.MM.yy HH:mm:ss z"

print(formatter.string(from:Date()))

That would output

01.04.23 17:12:25 GMT

For today, 1 April 2023, at about 17:12 GMT. (It's about 13:12 in my local time, which is EDT, or GMT-4.)