在2行上格式化日期 [英] Format date on 2 lines

查看:48
本文介绍了在2行上格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望日期在2行上

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

我在字符串中添加了时间,但我想在"dd"之前开始新行

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

示例: h:mma \ ndd MMMM yyyy

应该是:

7:12 PM

7:12PM

2015年5月19日

19 May 2015

.dateFormat 中, \ n 不起作用...唯一的方法是检测PM和19之间的第一个空格在哪里并替换 \ n .怎么做?

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 ?

它必须在地球上的每个时区工作.这意味着我不能使用AM/PM进行分离...

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

推荐答案

您的代码应该可以工作.也许让您感到困惑,例如,如果您在操场上检查返回值的值,则该值是这样的:

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)
}

并使用 println 调用值:

println(smdt2(NSDate()))

打印出的值是这样的:

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)"
}

这篇关于在2行上格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆