【问题标题】:Convert current time to local time in date format(Without converting it to string) in swift快速将当前时间转换为日期格式的本地时间(不将其转换为字符串)
【发布时间】:2022-04-19 04:16:12
【问题描述】:

我想将当前时间(UTC)转换为我的本地时区。但我不希望它是字符串,我希望它是日期格式本身。

我写了以下代码:

let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

在那之后,大多数人都这样做了

let dateString = dateFormatter.string(from: now)

没关系,我在本地时区得到了正确的时间,但是是字符串格式的。我想要日期格式。

再次,如果我这样做了

let currentDateInLocal = dateFormatter.date(from: dateString) //converting string to date

我正在获取 UTC 格式的日期。如何以日期格式获取本地时区的日期?

【问题讨论】:

  • 如果您通过print确认currentDateInLocal 是什么,请知道Dates 没有关联的时区,当您使用print 时,它将始终以UTC 显示. currentDateInLocal 只是一个时间点,但您解释该时间点所在的时区是完全独立的。
  • print(currentDateInLocal.description(with: .current))
  • 您需要分开两件事:timeZone 适用于日期。 dateFormat 适用于字符串。如果您想对日期进行操作(并且对字符串不感兴趣),请忘记格式,只需转换时区即可。这里描述了一堆方法:stackoverflow.com/questions/38641982/…
  • @thiscommunityistoxic 感谢帮助的人。完成

标签: swift datetime type-conversion


【解决方案1】:

您说“我想将当前时间(以 UTC 表示)转换为我的本地时区。但我不希望它是字符串,我希望它本身是日期格式。”

Date 对象没有时区。 Date 记录了世界任何地方的瞬间。想象一下,在同一瞬间,全世界的天空都出现了一道明亮的闪光。那是什么时候发生的?这取决于您所在的时区。但是,Date 对象可以捕获该瞬间。如果您想描述事件发生的时间,您可以将该日期转换为特定时区。

所以你的问题真的没有意义。

我建议使用 DateFormatter 类方法 localizedString(from:dateStyle:timeStyle:)显示您当地时区的日期:

例如

print(DateFormatter.localizedString(
  from: Date(), 
  dateStyle: .medium, 
  timeStyle: .medium))

这使您可以在本地时区查看Date 对象,而无需创建DateFormatter

【讨论】:

  • 查看我的答案中的代码,使用DateFormatter.localizedString(from:dateStyle:timeStyle:)
【解决方案2】:

我知道您说过您不希望它采用字符串格式,但是您可以简单地将其转换为日期对象。

欢迎您使用这个,我根据我自己的字符串格式创建了这个函数,将其更改为您需要的任何内容并繁荣。享受

//this function will allow you to easily convert your date string into readable current context
func convertDateToNow(createdAt:String) -> String{
    //create a date to represent the seconds since the start of the internet
    let currentDate = Date().timeIntervalSince1970
    //create a dateformatter
    let dateFormatter = DateFormatter()
    //use the locale on the device to set the the related time
    dateFormatter.locale = Locale.current
    //set the formate of which our date will be coming in at
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    
    //create a created at date for the post based off its createdAt date and get the seconds since the start of the internet
    let createdDate = dateFormatter.date(from: "\(createdAt)")?.timeIntervalSince1970
    
    //now we are left with two values depending on age of post either a few thousands off or it could be years in seconds. so we minus the current date on the users phone seconds from the created date seconds and voilla
    let secondsDifference = currentDate - createdDate!
    //use our specially created function to convert the seconds difference into time values
    let (d,h,m,s) = secondsToHoursMinutesSeconds(seconds: Int(secondsDifference))
    //test the values
    //        print("d:",d)
    //        print("h:",h)
    //        print("m:",m)
    //        print("s:",s)
    //
    
    //this will hold the final output of the string
    var finalDateLabel:String!
    
    //set the datelabel on the cell accordingly
    //create arithmetic for the date features
    if d != 0 {
        
        //check to see if the label is a day old
        if d == 1 {
            finalDateLabel = "\(d) day ago"
        }
    }else if h != 0{
        //set the date label
        finalDateLabel = "\(h) hour ago"
        if h == 1 {
            finalDateLabel = "\(h) hour ago"
        }else if h >= 2 {
            finalDateLabel = "\(h) hours ago"
        }
    }else if m != 0{
        //set the date label
        finalDateLabel = "\(m) minutes ago"
        if m == 1 {
            finalDateLabel = "\(m) minute ago"
        }
    }else if s != 0{
        //set the date label
        finalDateLabel = "\(s) seconds ago"
        if s == 1 {
            finalDateLabel = "\(s) second ago"
        }
    }
    
    return finalDateLabel
    
}

//to help convert the story
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int ,Int, Int, Int) {
    return (seconds / 86400, seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多