0

I want to convert current time(in UTC) to my local time zone. But I don't want it in string I want it in date format itself.

I have written following code:

let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

Now after that, mostly people have done

let dateString = dateFormatter.string(from: now)

Its okay, I am getting correct time in my local timezone but in string format. I want it in date format.

Again, if I do

let currentDateInLocal = dateFormatter.date(from: dateString) //converting string to date

I am getting the date in UTC format. How I can get the date in local timezone in date format?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • If you're confirming what `currentDateInLocal` is by `print`ing it, know that `Date`s have no associated time zone, and when you `print` one it will always display in UTC. `currentDateInLocal` is just a point in time, but the time zone you interpret that point in time in is entirely separate. – Itai Ferber Feb 22 '22 at 14:58
  • `print(currentDateInLocal.description(with: .current))` – Leo Dabus Feb 22 '22 at 15:04
  • You need to separate 2 things: the _timeZone_ applies to date. The _dateFormat_ applies to string. If you want to operate on date (and not interested in strings), forget format, and just convert the time zone. A bunch of methods is described here: https://stackoverflow.com/questions/38641982/converting-date-between-timezones-swift – timbre timbre Feb 22 '22 at 15:44

2 Answers2

1

You said "I want to convert current time(in UTC) to my local time zone. But I don't want it in string I want it in date format itself."

A Date object does not have a time zone. A Date records an instant in time, anywhere in the world. Imagine there is a bright flash in the sky all over the world at the same instant. What time did that happen? It depends on the time zone you are in. However, a Date object could capture that instant. You'd then convert that Date to a specific time zone if you wanted to describe the time of day the event occurred.

So your question doesn't really make sense.

I suggest using the DateFormatter class method localizedString(from:dateStyle:timeStyle:) to display a date in your local time zone:

e.g.

print(DateFormatter.localizedString(
  from: Date(), 
  dateStyle: .medium, 
  timeStyle: .medium))

That lets you view a Date object in your local time zone without needing to create a DateFormatter.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

I know you said you don't want it in a string format, however you can simply convert it over after to a date object.

you're welcome to use this, i created this function based on my own string format, change that to whatever you need and boom. enjoy

//this function will allow you to easily convert your date string into readable current context
func convertDateToNow(createdAt:String) -> String{
    //create a date to represent the seconds since the start of the internet
    let currentDate = Date().timeIntervalSince1970
    //create a dateformatter
    let dateFormatter = DateFormatter()
    //use the locale on the device to set the the related time
    dateFormatter.locale = Locale.current
    //set the formate of which our date will be coming in at
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    
    //create a created at date for the post based off its createdAt date and get the seconds since the start of the internet
    let createdDate = dateFormatter.date(from: "\(createdAt)")?.timeIntervalSince1970
    
    //now we are left with two values depending on age of post either a few thousands off or it could be years in seconds. so we minus the current date on the users phone seconds from the created date seconds and voilla
    let secondsDifference = currentDate - createdDate!
    //use our specially created function to convert the seconds difference into time values
    let (d,h,m,s) = secondsToHoursMinutesSeconds(seconds: Int(secondsDifference))
    //test the values
    //        print("d:",d)
    //        print("h:",h)
    //        print("m:",m)
    //        print("s:",s)
    //
    
    //this will hold the final output of the string
    var finalDateLabel:String!
    
    //set the datelabel on the cell accordingly
    //create arithmetic for the date features
    if d != 0 {
        
        //check to see if the label is a day old
        if d == 1 {
            finalDateLabel = "\(d) day ago"
        }
    }else if h != 0{
        //set the date label
        finalDateLabel = "\(h) hour ago"
        if h == 1 {
            finalDateLabel = "\(h) hour ago"
        }else if h >= 2 {
            finalDateLabel = "\(h) hours ago"
        }
    }else if m != 0{
        //set the date label
        finalDateLabel = "\(m) minutes ago"
        if m == 1 {
            finalDateLabel = "\(m) minute ago"
        }
    }else if s != 0{
        //set the date label
        finalDateLabel = "\(s) seconds ago"
        if s == 1 {
            finalDateLabel = "\(s) second ago"
        }
    }
    
    return finalDateLabel
    
}

//to help convert the story
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int ,Int, Int, Int) {
    return (seconds / 86400, seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}