Search This Blog

Tuesday, November 1, 2016

iOS Swift. How to work with DateFormatter

How to display date in specific format. For example, 01 August 1989,  or in specific locale (Russian: 1 августа 1989) or in specific timezone(MSK or PST)
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy HH:mm"
label1.text = "With Format: \(dateFormatter.string(from: date))"
        
let locale = Locale(identifier: "ru")
dateFormatter.locale = locale
label2.text = "With RU Locale:  \(dateFormatter.string(from: date))"
        
let timeZone = TimeZone(abbreviation: "MSK")
dateFormatter.timeZone = timeZone
label3.text = "With MSK TimeZone: \(dateFormatter.string(from: date))"

Result


What if we get string with data in specific format and we need to display it in other format(and in specific timezone and specific locale). 

For example, 
input format: yyyy-MM-dd'T'HH:mm:ss.SSSZ
output format: dd MMMM yyyy HH:mm

Firstly, we set input format to DateFormatter and convert input string to date. After that we set nre format and convert date to new string.
 let dateStr = "2016-10-31T14:51:21.780+08:00"
 label4.text = "Before: \(dateStr)"
 let dateFormatter = DateFormatter()
 dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        
 let timeZone = TimeZone(abbreviation: "MSK")
 dateFormatter.timeZone = timeZone
        
 let locale = Locale(identifier: "ru")
 dateFormatter.locale = locale
        
 let date = dateFormatter.date(from: dateStr)
        
 dateFormatter.dateFormat = "dd MMMM yyyy HH:mm"
 let formattedDateStr = dateFormatter.string(from: date!)
        
 label5.text = "After: \(formattedDateStr)"

Conversion Result


6 comments:

  1. You wrote an amazing article. I am amazed, your efforts are showing in the article. I hope in future I will see more Articles from you.
    -Custom Website Design

    ReplyDelete
  2. Your article is one of its kind which explained every bit of Custom Build Website. looking for further valuable articles from you

    ReplyDelete
  3. Thank you for writing this blog and giving this vital and useful information. Best Custom Websites

    ReplyDelete
  4. Good content. I was looking for this type of content. Saved my time for further search.
    You should always provide that type of content. I appreciate your determination to give the students a good title.Custom Designed Websites

    ReplyDelete
  5. Excellent website. This is the first time I've visited this blog, and it's fantastic. The main thing is that the content in this blog is written in a clear and intelligible manner.
    SEO Agency

    ReplyDelete