我正在为一个用swift编写的应用程序工作,我想操纵日期和时间
let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .ShortStyle, timeStyle: .ShortStyle)
返回
2/12/15, 11:27 PM
如果我想要一个不同格式的日期和时间,例如欧洲格式的日期,如dd / mm / yy和没有AM和PM的24小时格式的小时,我可以使用或有一些功能使用N字符串重新排序各种元素?
答案 0 :(得分:56)
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
}
编辑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
}
答案 1 :(得分:29)
如前所述,您必须使用DateFormatter格式化Date对象。最简单的方法是创建一个只读的计算属性Date扩展名。
只读计算属性
具有getter但没有setter的计算属性称为a 只读计算属性。始终是只读计算属性 返回一个值,可以通过点语法访问,但不能 设置为不同的值。
注意:强>
您必须声明计算属性 - 包括只读计算 properties - 作为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)
}
}
要将其转换回来,您可以创建另一个只读的计算属性,但作为字符串扩展名:
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)
}
}
用法:
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"
}
答案 2 :(得分:12)
正如扎普所说,你需要遵循文件。不可否认,与其他类引用相比,它可能不是最直接的。简短的回答是,您使用Date Field Symbol Table来确定您想要的格式。一旦你这样做了:
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())
如果您需要将字符串日期转换为NSDate,您还需要能够使用该表。
let dateAsString = "02/12/15, 16:48"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M/d/yyyy, H:mm"
let date = dateFormatter.dateFromString(dateAsString)
答案 3 :(得分:9)
格式化字符串的当前日期时间:
' loop example per your case
For Col = 1 To 4
Range(Cells(1, Col), Cells(1, Col + 3)).Select
Next Col
答案 4 :(得分:4)
1)创建可约会协议
protocol Dateable {
func userFriendlyFullDate() -> String
func userFriendlyHours() -> String
}
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)使用
let currentDate: Date = Date()
let stringDate: String = currentDate.userFriendlyHours()
// Print 15:16
答案 5 :(得分:3)
我使用了与@ iod07类似的方法,但作为扩展。 另外,我在评论中添加了一些解释,以了解它是如何工作的。
基本上,只需在视图控制器的顶部或底部添加它。
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
}
}
示例强>
我们假设您要将"16 05 05"
转换为"Thursday 05 May 2016"
,并将您的约会日期声明为let date = "16 06 05"
然后只需拨打电话:
let newDate = NSString.convertFormatOfDate(date, originalFormat: "yy MM dd", destinationFormat: "EEEE dd MMMM yyyy")
希望它有所帮助!
答案 6 :(得分:3)
您已找到NSDateFormatter
,只需阅读相关文档。
NSDateFormatter Class Reference
格式字符定义
见:ICU Formatting Dates and Times
另外:Date Field SymbolTable.。
答案 7 :(得分:2)
斯威夫特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))"
有关更多格式,请查看此link到包含所有可用格式的codingExplorer表。每个日期组件都有几个选项,例如:
年:
几乎每个组件都有2-4个选项,使用第一个字母表示格式(日期为" d&#34 ;,小时为" h"等)。然而,月是资本" M",因为小写" m"保留一分钟。还有一些其他例外,请查看链接!
答案 8 :(得分:0)
new Date(year,month,day,0,0,0,0)
是当地时间(作为输入)
new Date(year,month,day)
是 UTC
我正在使用一个函数来获得 YYYY-MM-DD
格式以在 iOS 网络上兼容,但在比较中使用时也是 UTC(不是由 getFullYear 或类似链接)我已经发现最好只使用上面的强(小时,分钟,秒,毫秒)构建日历,使用 Date 对象和本地引用进行计算
export const zeroPad = (num) => {
var res = "0";
if (String(num).length === 1) {
res = `0${num}`;
} else {
res = num;
}
return res;
};
答案 9 :(得分:0)
在一处添加了一些格式。希望有人得到帮助。
Xcode 12-Swift 5.3
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var dateFromStr = dateFormatter.date(from: "12:16:45")!
dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16
dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM
dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000
dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000
dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000
dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM
dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000
dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00
//Output: Customisable AP/PM symbols
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"
//Output: Pm
// Usage
var timeFromDate = dateFormatter.string(from: dateFromStr)
print(timeFromDate)
答案 10 :(得分:0)
class ViewController: UIViewController {
//timePicker
@IBOutlet weak var lblTime: UILabel!
@IBOutlet weak var timePicker: UIDatePicker!
@IBOutlet weak var cancelTime_Btn: UIBarButtonItem!
@IBOutlet weak var donetime_Btn: UIBarButtonItem!
@IBOutlet weak var toolBar: UIToolbar!
//Date picker
// @IBOutlet weak var datePicker: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
ishidden(bool: true)
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "HH:mm a" //"hh:mm a"
lblTime.text = dateFormatter2.string(from: timePicker.date)
}
@IBAction func selectTime_Action(_ sender: Any) {
timePicker.datePickerMode = .time
ishidden(bool: false)
}
@IBAction func timeCancel_Action(_ sender: Any) {
ishidden(bool: true)
}
@IBAction func timeDoneBtn(_ sender: Any) {
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "HH:mm a"//"hh:mm"
let str = dateFormatter1.string(from: timePicker.date)
lblTime.text = str
ishidden(bool: true)
}
func ishidden(bool:Bool){
timePicker.isHidden = bool
toolBar.isHidden = bool
}
}
答案 11 :(得分:0)
指定locale explicitly
既麻烦又困难。您永远不知道将在哪里使用您的应用程序。因此,我认为最好将locale
设置为Calender.current.locale
并使用DateFormatter
setLocalizedDateFormatFromTemplate
方法。
使用指定的收件人区域设置从模板设置日期格式。 -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")
答案 12 :(得分:0)
这可能是一个旧线程,但是我最近正在处理日期时间,并且遇到了类似的问题,所以我最终创建了一个看起来像这样的我的实用程序,
该实用程序将使用字符串日期,并返回可选的日期对象
func toDate(dateFormat: DateFormatType) -> Date? {
let formatter = DateFormatter()
formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
formatter.dateFormat = dateFormat.rawValue
let temp = formatter.date(from: self)
return formatter.date(from: self)
}
DateFormatType
枚举看起来像这样
enum DateFormatType : String {
case type1 = "yyyy-MM-dd - HH:mm:ss"
case type2 = "dd/MM/yyyy"
case type3 = "yyyy/MM/dd"
}
我想在这里提到的一件事很重要
formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
添加此行非常重要,因为如果没有此行,DateFormatter
将使用它的默认转换来转换日期,并且如果您与远程团队合作并获得各种各样的信息,最终可能会看到不同的日期数据取决于日期的问题。
希望这会有所帮助
答案 13 :(得分:0)
imageSeries.data = [{
"minZoomLevel": 2,
"latitude": 28.340322,
"longitude": 77.922881,
"imageURL": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAABaCAMAAAAPdrEwAAAAY1BMVEX///8AAAD39/f19fUmJiYgICAdHR0sLCySkpL8/PwWFhbj4+Px8fEPDw/n5+ecnJw2Nja/v79zc3OKioqlpaW1tbVLS0t/f3/Gxsbd3d3Nzc3X19dUVFRubm6vr69oaGhAQEAk5whvAAAB+klEQVRYhe2Yi5KCIBSGBfGaJqmVabf3f8qVg02GYKgws83wzexOHekP+A+HwPP0aSltFzTXBz9QzwObV67RQG1Y+HJiqkXB/p8uBoVxxSSve8/bX9mrytisNCnTu/M3d/Y6bYwIZ9DRMnm9T0oYQrZdGaY37cahDkZRbBTuIqkKfF/UyT6hSXKGjNhNn+wgY87J9IkeB5iLo/zhEWblsEpYtE9kvZ0x+yCdXR0XytrEC4VbqrWmYfUvqlkZjPWhMdYMalapPStHtMAh8BopvBbYPSGvdPvheZChT0mGilTf7RPhdlZfWjX5qBLpAzUrn6tZ/k3XPhFu582f/e5oZb1sIvV4uX3fZmyGSmHnUIn265X7LUhasw6BfnbOACsiGK8IvuOVBnY8XL52UQ5UAmLo10tL3tWnI9y+BBsh4XaSbtiLUE6JMWg+/BRC1hh6bYGtO/6/APsf4LXxKXEafpDG6+ISJC6vist6LbYcelEp4qr2csi7R5EiTsbxSBGf4gejplgeD0Z7CSbyuJN20k7aSTtpJ+2knbSTdtJO+lelrR04VMeepXEJSw9xqris16HAcIQvFsZl2DtI/xoTr7fwmScmlYU8iUNz11qBkN1mbuI4tt2zi7XLOKtXiP2fueR4w6WDzGR6cLIApEML2YLTXrq2c/lZoPoPNtQibDMMVRwAAAAASUVORK5CYII=",
"width": 5,
"height": 5,
"label": "[font-size:10]Meerut[/]"
}];
从视图控制器文件中进行调用,如下所示。
extension String {
func convertDatetring_TopreferredFormat(currentFormat: String, toFormat : String) -> String {
let dateFormator = DateFormatter()
dateFormator.dateFormat = currentFormat
let resultDate = dateFormator.date(from: self)
dateFormator.dateFormat = toFormat
return dateFormator.string(from: resultDate!)
}
}
答案 14 :(得分:0)
let dateString = "1970-01-01T13:30:00.000Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.date(from: String(dateString.dropLast(5)))!
formatter.dateFormat = "hh.mma"
print(formatter.string(from: date))
如果您注意到我为此设定了.dateFormat = "hh.mma"
,那么您将只有时间。
结果:01.30PM
答案 15 :(得分:0)
这是可与Xcode 10.1(2019年2月23日)一起使用的解决方案:
import com.mysql.jdbc.Connection
答案 16 :(得分:0)
let usDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US"))
//usDateFormat now contains an optional string "MM/dd/yyyy"
let gbDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB"))
//gbDateFormat now contains an optional string "dd/MM/yyyy"
let geDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "de-DE"))
//geDateFormat now contains an optional string "dd.MM.yyyy"
您可以按照以下方式使用它来从设备获取当前格式:
let currentDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale.current)