-1

I currently have a class with this field:

let date:String = NSDate().description

and the resulting value is this format:

"2016-01-10 01:14:20 +0000"

But I want the value to simply look like this:

"January 1, 2016"

What's the quickest way to do this?

rigdonmr
  • 2,662
  • 3
  • 26
  • 40

2 Answers2

3

Make use of the NSDateFormatterStyle.LongStyle as value for the NSDateFormatter.dateStyle property:

let myDate = NSDate()

let formatter = NSDateFormatter()
formatter.dateStyle = .LongStyle

let dateAsString = formatter.stringFromDate(myDate)

print(dateAsString)
// January 10, 2016
dfrib
  • 70,367
  • 12
  • 127
  • 192
  • 1
    You may also want to cache the formatter instance if possible, since it's expensive to create. http://stackoverflow.com/questions/8832768/why-is-allocating-or-initializing-nsdateformatter-considered-expensive – Cheng-Yu Hsu Jan 10 '16 at 01:25
  • @ChengYuHsu Thanks for that feedback, that's a good point to think about. – dfrib Jan 10 '16 at 01:27
0
extension NSDate {
    struct Date {
        static let formatterDateLong: NSDateFormatter = {
            let formatter = NSDateFormatter()
            formatter.dateStyle = .LongStyle
            return formatter
        }()
    }
    var longStyleDate: String { return Date.formatterDateLong.stringFromDate(self) ?? "" }
}

NSDate().longStyleDate  // "January 9, 2016"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571