2

I want date to be on 2 lines

public func smdt(date:NSDate)->NSString{
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "h:mma dd MMMM yyyy"
    return dateFormatter.stringFromDate(date)
}

I add time in string, but I want to start new line before "dd"

Example: h:mma\ndd MMMM yyyy

Should be:

7:12PM

19 May 2015

In .dateFormat, \n doesn't work... The only way to be done is to detect where is the first whitespace between PM and 19 and replace it with \n. How it can be done ?

It has to work on every timezone on the earth. That means I can't use AM/PM for separating...

Community
  • 1
  • 1
Bogdan Bogdanov
  • 882
  • 11
  • 36
  • 79

1 Answers1

6

Your code should work. Maybe it confuses you, that if you check the values of your return-values from within the playground for example, the value is like that:

"6:21PM\n19 May 2015"

But if I use your code like that:

public func smdt(date:NSDate)->NSString{
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "h:mma\ndd MMMM yyyy"
    return dateFormatter.stringFromDate(date)
}

And call the value by using println:

println(smdt2(NSDate()))

The value printed out is like that:

6:22PM
19 May 2015

So you can use your code like you tried already.

But you also could split the hour and day/month like that and concate it later:

public func smdt(date:NSDate)->NSString{
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "h:mma"
    var hour = dateFormatter.stringFromDate(date)
    dateFormatter.dateFormat = "dd MMMM yyyy"

    var otherPart = dateFormatter.stringFromDate(date)
    return "\(hour)\n\(otherPart)"
}
Christian
  • 22,585
  • 9
  • 80
  • 106