Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/118.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
时间格式包含iOS 12.2不支持的冒号(:)_Ios_Swift_Nsdateformatter - Fatal编程技术网

时间格式包含iOS 12.2不支持的冒号(:)

时间格式包含iOS 12.2不支持的冒号(:),ios,swift,nsdateformatter,Ios,Swift,Nsdateformatter,我使用的是iphonese,它包含ios12.2。我正在将日期转换为以下时间格式(h:MM a),该格式转换正确的时间,但删除了小时和分钟之间的冒号(:) 我的代码如下所示,用于转换时间: static func getDateInWithoutTimeZone(format: String, from timeStamp: Int64) -> String? { let date = Date(timeIntervalSince1970: TimeInterval(timeSta

我使用的是
iphonese
,它包含
ios12.2
。我正在将日期转换为以下时间格式(
h:MM a
),该格式转换正确的时间,但删除了小时和分钟之间的冒号(:)

我的代码如下所示,用于转换时间:

static func getDateInWithoutTimeZone(format: String, from timeStamp: Int64) -> String? {
    let date = Date(timeIntervalSince1970: TimeInterval(timeStamp))
    let dateFormatter = DateFormatter()
    dateFormatter.locale = NSLocale.current
    dateFormatter.dateFormat = format //Specify your format that you want
    return dateFormatter.string(from: date)
}
我使用这个方法来转换时间,其中时间戳包含
UNIX
时间值,比如
1555395758

我使用上述函数如下所示:

guard let time = Date.getDateInWithoutTimeZone(format: "h:MM a", from: 1555395758) else {
    return
}
并获得以下输出:

1104 AM

我做错什么了吗?还是iOS 12.2出现问题?

只需将日期格式
h:MM a
更改为
hh:MM a

请参考下面的代码

static func getDateInWithoutTimeZone(format: String, from timeStamp: Int64) -> String? {
    let date = Date(timeIntervalSince1970: TimeInterval(timeStamp))
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = format //Specify your format that you want
    return dateFormatter.string(from: date)
}

guard let time = getDateInWithoutTimeZone(format: "hh:mm a", from: 1555395758) else {
    return
}
print(time)

代表月,不是分钟


如果要显示小时和分钟(加上am/pm),格式字符串应为
“h:mm a”
。无论何时,如果要包含不是直接格式说明符的字符,建议将其包含在单引号中。因此,您也可以使用
“h”:“mm a”
。请注意,您在示例中使用的说明符包括
MM
(大写字母M),表示月份,而不是分钟。

MM->month-not-minutes我尝试了您的代码我没有遇到任何问题,对我来说效果很好,更改您的格式
dateFormat=“h:MM a”
奇怪。。。当我在操场上运行你的代码时,我得到了
8:22 AM
。是的,我将
“h:MM a”
更改为
“h:MM a”
,但这并不重要,冒号作为分隔符仍然存在……如果要正确处理12小时与24小时,必须将locale设置为POSIX。否则格式将被系统设置覆盖。嘿@sagar,请检查我的答案。你的设备是24小时制的,这就是为什么你有“上午1104点”。value.locale应该是
“en\u US\u POSIX”
。顺便说一句,此方法每次调用时都会创建一个新的日期格式化程序。@iMHiteshSurani,您在使用iOS 12.2的Real设备上试用过吗?是的,使用iOS 12.1的iPhone 8P在我的设备上运行良好。此外,检查了12小时和24小时格式,并使用我提到的验证,您可以遵循此处的一般建议(这意味着在这种情况下不需要它)。