Swift - iOS - 不同格式的日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28489227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - iOS - Dates and times in different format
提问by GioB
I am working for an application written in swift and i want to manipulate dates and times
我正在为一个用 swift 编写的应用程序工作,我想操纵日期和时间
let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .ShortStyle, timeStyle: .ShortStyle)
returns
返回
2/12/15, 11:27 PM
if I want date and time in a different format,for example the date in a european format like dd/mm/yy and the hours in the 24h format without AM and PM there is some function that i can use or i have to use N Strings to reorder the various elements?
如果我想要不同格式的日期和时间,例如欧洲格式的日期,如 dd/mm/yy 和 24h 格式的小时,没有 AM 和 PM,那么我可以使用一些功能,或者我必须使用 N字符串重新排序各种元素?
回答by idris y?ld?z
func convertDateFormater(date: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
guard let date = dateFormatter.dateFromString(date) else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let timeStamp = dateFormatter.stringFromDate(date)
return timeStamp
}
Edit for Swift 4
为 Swift 4 编辑
func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "yyyy MMM HH:mm EEEE"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
return timeStamp
}
回答by Leo Dabus
As already mentioned you have to use DateFormatter to format your Date objects. The easiest way to do it is creating a read-only computed property Date extension.
如前所述,您必须使用 DateFormatter 来格式化 Date 对象。最简单的方法是创建一个只读的计算属性 Date 扩展。
Read-Only Computed Properties
A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.
只读计算属性
具有 getter 但没有 setter 的计算属性称为只读计算属性。只读计算属性总是返回一个值,可以通过点语法访问,但不能设置为不同的值。
Note:
笔记:
You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.
You can simplify the declaration of a read-only computed property by removing the get keyword and its braces:
您必须使用 var 关键字将计算属性(包括只读计算属性)声明为变量属性,因为它们的值不是固定的。let 关键字仅用于常量属性,表示它们的值一旦被设置为实例初始化的一部分就不能更改。
您可以通过删除 get 关键字及其大括号来简化只读计算属性的声明:
extension Formatter {
static let date = DateFormatter()
}
extension Date {
var europeanFormattedEn_US : String {
Formatter.date.calendar = Calendar(identifier: .iso8601)
Formatter.date.locale = Locale(identifier: "en_US_POSIX")
Formatter.date.timeZone = .current
Formatter.date.dateFormat = "dd/M/yyyy, H:mm"
return Formatter.date.string(from: self)
}
}
To convert it back you can create another read-only computed property but as a string extension:
要将其转换回来,您可以创建另一个只读计算属性,但作为字符串扩展名:
extension String {
var date: Date? {
return Formatter.date.date(from: self)
}
func dateFormatted(with dateFormat: String = "dd/M/yyyy, H:mm", calendar: Calendar = Calendar(identifier: .iso8601), defaultDate: Date? = nil, locale: Locale = Locale(identifier: "en_US_POSIX"), timeZone: TimeZone = .current) -> Date? {
Formatter.date.calendar = calendar
Formatter.date.defaultDate = defaultDate ?? calendar.date(bySettingHour: 12, minute: 0, second: 0, of: Date())
Formatter.date.locale = locale
Formatter.date.timeZone = timeZone
Formatter.date.dateFormat = dateFormat
return Formatter.date.date(from: self)
}
}
Usage:
用法:
let dateFormatted = Date().europeanFormattedEn_US //"29/9/2018, 16:16"
if let date = dateFormatted.date {
print(date.description(with:.current)) // Saturday, September 29, 2018 at 4:16:00 PM Brasilia Standard Time\n"\
date.europeanFormattedEn_US // "29/9/2018, 16:27"
}
let dateString = "14/7/2016"
if let date = dateString.toDateFormatted(with: "dd/M/yyyy") {
print(date.description(with: .current))
// Thursday, July 14, 2016 at 12:00:00 PM Brasilia Standard Time\n"
}
回答by Jeremy Pope
As Zaph stated, you need to follow the documentation. Admittedly it may not be the most straightforward when compared to other class references. The short answer is, you use Date Field Symbol Tableto figure out what format you want. Once you do:
正如 Zaph 所说,您需要遵循文档。诚然,与其他类引用相比,它可能不是最直接的。简短的回答是,您使用日期字段符号表来确定您想要的格式。一旦你这样做:
let dateFormatter = NSDateFormatter()
//the "M/d/yy, H:mm" is put together from the Symbol Table
dateFormatter.dateFormat = "M/d/yy, H:mm"
dateFormatter.stringFromDate(NSDate())
You'll also need to be able to use the table if you need to convert a date that is a string into an NSDate.
如果您需要将字符串日期转换为 NSDate,您还需要能够使用该表。
let dateAsString = "02/12/15, 16:48"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M/d/yyyy, H:mm"
let date = dateFormatter.dateFromString(dateAsString)
回答by Atif Mahmood
Current date time to formated string:
格式化字符串的当前日期时间:
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss a"
let convertedDate: String = dateFormatter.string(from: currentDate) //08/10/2016 01:42:22 AM
回答by zaph
You have already found NSDateFormatter
, just read the documentation on it.
您已经找到了NSDateFormatter
,只需阅读有关它的文档即可。
NSDateFormatter Class Reference
For format character definitions
See: ICU Formatting Dates and Times
Also: Date Field SymbolTable..
有关格式字符定义,
请参阅:ICU 格式化日期和时间
另请参阅:日期字段符号表。.
回答by Ludovic
If you want to use protocol oriented programming (Swift 3)
如果你想使用面向协议的编程(Swift 3)
1) Create a Dateable protocol
1)创建一个可日期的协议
protocol Dateable {
func userFriendlyFullDate() -> String
func userFriendlyHours() -> String
}
2) Extend Date class and implement the Dateable protocol
2)扩展Date类并实现Dateable协议
extension Date: Dateable {
var formatter: DateFormatter { return DateFormatter() }
/** Return a user friendly hour */
func userFriendlyFullDate() -> String {
// Customize a date formatter
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.timeZone = TimeZone(abbreviation: "UTC")
return formatter.string(from: self)
}
/** Return a user friendly hour */
func userFriendlyHours() -> String {
// Customize a date formatter
formatter.dateFormat = "HH:mm"
formatter.timeZone = TimeZone(abbreviation: "UTC")
return formatter.string(from: self)
}
// You can add many cases you need like string to date formatter
}
3) Use it
3)使用它
let currentDate: Date = Date()
let stringDate: String = currentDate.userFriendlyHours()
// Print 15:16
回答by Benjamin Tourin
Here is a solution that works with Xcode 10.1 (FEB 23 2019) :
这是一个适用于 Xcode 10.1(2019 年 2 月 23 日)的解决方案:
func getCurrentDateTime() {
let now = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "fr_FR")
formatter.dateFormat = "EEEE dd MMMM YYYY"
labelDate.text = formatter.string(from: now)
labelDate.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
labelDate.textColor = UIColor.lightGray
let text = formatter.string(from: now)
labelDate.text = text.uppercased()
}
回答by tsnkff
I used the a similar approach as @iod07, but as an extension. Also, I added some explanations in the comments to understand how it works.
我使用了与@iod07 类似的方法,但作为扩展。另外,我在评论中添加了一些解释以了解它是如何工作的。
Basically, just add this at the top or bottom of your view controller.
基本上,只需在视图控制器的顶部或底部添加它。
extension NSString {
class func convertFormatOfDate(date: String, originalFormat: String, destinationFormat: String) -> String! {
// Orginal format :
let dateOriginalFormat = NSDateFormatter()
dateOriginalFormat.dateFormat = originalFormat // in the example it'll take "yy MM dd" (from our call)
// Destination format :
let dateDestinationFormat = NSDateFormatter()
dateDestinationFormat.dateFormat = destinationFormat // in the example it'll take "EEEE dd MMMM yyyy" (from our call)
// Convert current String Date to NSDate
let dateFromString = dateOriginalFormat.dateFromString(date)
// Convert new NSDate created above to String with the good format
let dateFormated = dateDestinationFormat.stringFromDate(dateFromString!)
return dateFormated
}
}
Example
例子
Let's say you want to convert "16 05 05"
to "Thursday 05 May 2016"
and your date is declared as follow let date = "16 06 05"
假设您要转换"16 05 05"
为"Thursday 05 May 2016"
并且您的日期声明如下let date = "16 06 05"
Then simply call call it with :
然后简单地调用调用它:
let newDate = NSString.convertFormatOfDate(date, originalFormat: "yy MM dd", destinationFormat: "EEEE dd MMMM yyyy")
Hope it helps !
希望能帮助到你 !
回答by Dave G
Swift 3:
斯威夫特 3:
//This gives month as three letters (Jun, Dec, etc)
let justMonth = DateFormatter()
justMonth.dateFormat = "MMM"
myFirstLabel.text = justMonth.string(from: myDate)
//This gives the day of month, with no preceding 0s (6,14,29)
let justDay = DateFormatter()
justDay.dateFormat = "d"
mySecondLabel.text = justDay.string(from: myDate)
//This gives year as two digits, preceded by an apostrophe ('09, '16, etc)
let justYear = DateFormatter()
justYear.dateFormat = "yy"
myThirdLabel.text = "'\(justYear.string(from: lastCompDate))"
For more formats, check out this linkto a codingExplorer table with all the available formats. Each date component has several options, for example:
有关更多格式,请查看此链接,指向包含所有可用格式的 codingExplorer 表。每个日期组件都有几个选项,例如:
Year:
年:
- "y" - 2016 (early dates like year 1 would be: "1")
- "yy" - 16 (year 1: "01"
- "yyy" - 2016 (year 1: "001")
- "yyyy" - 2016 (year 1: "0001")
- “y” - 2016 年(像第 1 年这样的早期日期是:“1”)
- “yy” - 16(第 1 年:“01”
- “yyy” - 2016 年(第 1 年:“001”)
- “yyyy” - 2016 年(第 1 年:“0001”)
Pretty much every component has 2-4 options, using the first letter to express the format (day is "d", hour is "h", etc). However, month is a capital "M", because the lower case "m" is reserved for minute. There are some other exceptions though, so check out the link!
几乎每个组件都有 2-4 个选项,使用第一个字母来表示格式(天是“d”,小时是“h”等)。但是,月份是大写的“M”,因为小写的“m”是为分钟保留的。但是还有其他一些例外,所以请查看链接!
回答by mahan
iOS 8+
iOS 8+
It is cumbersome and difficult to specify locale explicitly
. You never know where your app will be used. So I think, it is better to set locale
to Calender.current.locale
and use DateFormatter
's
setLocalizedDateFormatFromTemplate
method.
它既麻烦又难以指定locale explicitly
。您永远不知道您的应用程序将在哪里使用。所以我认为,最好设置locale
为Calender.current.locale
并使用 DateFormatter
的
setLocalizedDateFormatFromTemplate
方法。
setLocalizedDateFormatFromTemplate(_:)
setLocalizedDateFormatFromTemplate(_:)
Sets the date format from a template using the specified locale for the receiver. - developer.apple.com
使用接收器的指定区域设置从模板设置日期格式。- developer.apple.com
extension Date {
func convertToLocaleDate(template: String) -> String {
let dateFormatter = DateFormatter()
let calender = Calendar.current
dateFormatter.timeZone = calender.timeZone
dateFormatter.locale = calender.locale
dateFormatter.setLocalizedDateFormatFromTemplate(template)
return dateFormatter.string(from: self)
}
}
Date().convertToLocaleDate(template: "dd MMMM YYYY")