将JSON字符串转换为日期时间并比较swift
我有两个问题: 1) 我想将JSON字符串转换为时间。我得到了JSON字符串,但无法将其转换为时间。 以下是我的代码:将JSON字符串转换为日期时间并比较swift,json,swift,datetime,nsdateformatter,Json,Swift,Datetime,Nsdateformatter,我有两个问题: 1) 我想将JSON字符串转换为时间。我得到了JSON字符串,但无法将其转换为时间。 以下是我的代码: 这里应该是您的JSON[“状态”:200,“数据”:15:55,“消息”:及时] 我得到的“数据”是字符串,我想把数据转换成实际时间 if let datetime = json["data"] as? String { print("on CLick of in_time BUtton : \(datetime)") let formattter = Date
这里应该是您的JSON[“状态”:200,“数据”:15:55,“消息”:及时]
我得到的“数据”是字符串,我想把数据转换成实际时间
if let datetime = json["data"] as? String {
print("on CLick of in_time BUtton : \(datetime)")
let formattter = DateFormatter()
formattter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formattter.date(from: datetime)
print("form : \(formattter)")
print("Date : \(datetime)")
}
2) 我有一个宽限期,我想将它与服务器时间进行比较,我将通过json获得如何实现它,请帮助!!!
宽限期为10:30,如@Dávid pászor所说,您可以使用like:
if let strResp = json["data"]{
let strDate = "\(strResp!)" //15:55
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm" // Pass any format here you want according to your date response
let convDate = dateFormatter.date(from: strDate)
print(convDate!)
}
当JSON显然只包含分钟精度的时间时,为什么要使用完整的日期格式?只需将
dateFormat
设置为HH:mm
。即使使用该设置,我在打印“表单”form:
时仍会出错。打印formatter
时,您希望看到什么?如果是在宽限时间之前或之后,我如何将时间与宽限时间进行比较。因为在安卓系统中,我使用它作为datetime.before(gracetime)
我可以在这里使用什么?@SandeshZote您得到了什么错误?您只需使用比较运算符比较Date
对象,即datetime
。您还应该打印formatter
,这毫无意义,您应该打印formatter.date(from:datetime)
。他还应该将区域设置设置为formatter.locale=locale(标识符:“en\u US\u POSIX”)
让时间=formatter.date(from:datetime)打印(“form:\(字符串(描述:time)))并将值获取为表单:可选(2000-01-01 11:04:00+0000)
您需要使用if let
而不是let
打开可选结果。您还需要使用日期格式化程序将日期转换回字符串formatter.string(from:time)
@LeoDabus很抱歉,我没有理解如果您打印日期,您将获得UTC时间表示形式。如果您想查看当地时间,则需要使用日期格式化程序如果let time=formatter.date(from:datetime){
并且在打印时打印(formatter.string(from:time))