使用各种格式将时间戳转换为日期 [英] Convert Timestamp to Date with various formats Swift

查看:322
本文介绍了使用各种格式将时间戳转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:-

let addedTime = dictMessage?.object(forKey: "added_time") as? String
let timeinterval : TimeInterval = (addedTime as NSString).doubleValu                
let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)
let dateFormater : DateFormatter = DateFormatter()              
dateFormater.dateFormat = "dd-MMM-yyyy hh:mm a"
cellDetailsShop.lblTimeShop?.text = dateFormater.string(from: dateFromServer as Date)

我有一个json,并且从json im获得 Timestamp ,我已经将其转换为Date.Date,我收到它的日期显示在格式 dd-MMM-yyyy hh:mm a 。但是我想显示日期,例如date是今天,那么它将显示:今天04:55 PM ,如果日期是昨天,那么我将显示为:昨天5 PM ,如果在此之前它应显示为i正在从JSON检索。我搜索了各种链接,但找不到答案。有人可以帮助我。谢谢。

I have a json and from json i m getting Timestamp which i already converted to Date.Date which i am receiving it is showing in the format "dd-MMM-yyyy hh:mm a".But i want to show date like if date is of today then it will show :Today 04:55 PM,if date is of yesterday then i will show like: Yesterday 5 PM and if before that then it should show as i am retrieving from JSON. I searched various links but could not find the answer.Could someone help me.Thanks in advance.

推荐答案

从Calendar对象开始,您可以获取日期是今天还是昨天。
基于此,您可以根据需要设置String。
我创建了一个您需要的示例。下面的
是代码。

As from Calendar object you can get if the date is today or yesterday. based on that you can set String as you like. I've created an example like you need. below is code.

var yesterdayStr = "17-Jan-2018 10:23 AM"
var todayStr = "18-Jan-2018 10:23 AM"
var tomorrowStr = "19-Jan-2018 10:23 AM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy hh:mm a"
let yesterDaydate = dateFormatter.date(from: yesterdayStr)
let todayDate = dateFormatter.date(from: todayStr)
let tomorrowDate = dateFormatter.date(from: tomorrowStr)
let anotherDateFormatter = DateFormatter()
anotherDateFormatter.dateFormat = "hh:mm a"
if Calendar.current.isDateInYesterday(yesterDaydate!)
{
    let yesterdayDisplayString = "Yesterday, " + anotherDateFormatter.string(from: yesterDaydate!)
}
if Calendar.current.isDateInToday(todayDate!) {
    let todayDisplayString = "Today, " + anotherDateFormatter.string(from: todayDate!)
}
if Calendar.current.isDateInToday(tomorrowDate!) {

}
else {
    let anotherDisplayString = anotherDateFormatter.string(from: tomorrowDate!)
}

这是输出,

and here is output,

这篇关于使用各种格式将时间戳转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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