xcode Swift - 如何以秒为单位获取当前时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36073652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:38:25  来源:igfitidea点击:

Swift - How can I get the current time in seconds?

iosxcodeswifttimezonensdate

提问by user2163449

A user posts a comment in a different timezone and another user views the comment in different timezone. The time should be the same when converted back to the users timezone on their device.

一个用户在不同的时区发表评论,另一个用户在不同的时区查看评论。转换回用户设备上的时区时,时间应该相同。

Here's what I am trying but getting an "fatal error: unexpectedly found nil while unwrapping an Optional value". The error is happening in my distance time variable when its trying to subtract "time". I printed time before it executed and its saying "nil". Any help please?

这是我正在尝试但收到“致命错误:在解开可选值时意外发现 nil”的内容。当我尝试减去“时间”时,错误发生在我的距离时间变量中。我在它执行之前打印了时间并说“nil”。请问有什么帮助吗?

import UIKit

class EventCommentCell: UITableViewCell {

类 EventCommentCell: UITableViewCell {

var obj : EventCommentObj!

@IBOutlet var profileImage: UIImageView!
@IBOutlet var commentMessage: UITextView!
@IBOutlet var time: UILabel!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

func setData(){



    profileImage.layer.borderWidth = 1
    profileImage.layer.masksToBounds = false


    profileImage.layer.borderColor = UIColor(red: 0.125, green: 0.757, blue: 0.569, alpha: 1.0).CGColor
    profileImage.layer.cornerRadius = profileImage.frame.height/2
    profileImage.clipsToBounds = true

    print("The Image URL : \(obj.profileImage)")


    ImageLoader.sharedLoader.imageForUrl(obj.profileImage, completionHandler:{(image: UIImage?, url: String) in
        self.profileImage.image  = image
    })

    let message = "\(obj.username) \n\(obj.comment)"



    let attributedString = NSMutableAttributedString(string: message as String)

    let range: NSRange = (message as NSString).rangeOfString(obj.username as String)
    let range1: NSRange = (message as NSString).rangeOfString(obj.comment as String)
    let font = UIFont.boldSystemFontOfSize(commentMessage.font!.pointSize)

    attributedString.addAttribute(NSFontAttributeName, value: font, range: range)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.125, green: 0.757, blue: 0.569, alpha: 1.0), range: range)

    commentMessage.attributedText = attributedString

    time.text = getCreationTimeInt(obj.created_on)

}

func getCreationTimeInt(dateString : String) -> String{

    let dateFormatter = NSDateFormatter()
    dateFormatter.locale = NSLocale.currentLocale()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    dateFormatter.timeZone = NSTimeZone.systemTimeZone()


    let time = dateFormatter.dateFromString(dateString)?.timeIntervalSince1970

    let distanceTime = NSDate().timeIntervalSince1970 - time!

    let stringTime = returnDistanceTime(distanceTime)

    print("**** The time \(stringTime)", terminator: "")

    return stringTime

}

func returnDistanceTime(distanceTime : Double) -> String{

    var stringTime = ""

    if (distanceTime < 0) {
        stringTime = "0s"


    }else{
        if(distanceTime < 60){
            stringTime = "\(Int(distanceTime))s"


        }else{
            if(distanceTime < 3600){

                stringTime = "\(Int(distanceTime/60))m"

            }else{

                if(distanceTime < 3600*24){
                    stringTime = "\(Int(distanceTime/3600))h"

                }else{

                    if(distanceTime < 3600*24*7) {

                        stringTime = "\(Int(distanceTime/3600/24))d"

                    }else{
                        stringTime = "\(Int(distanceTime/3600/24/7))w"

                    }
                }
            }
        }
    }
    return stringTime
}

}

}

回答by Aaron

Welcome to stack overflow. I plugged what you had into a Playground and it worked perfectly. Here is what I have:

欢迎使用堆栈溢出。我将你拥有的东西插入游乐场,它运行良好。这是我所拥有的:

//: Playground - noun: a place where people can play

import Cocoa


func returnDistanceTime(distanceTime: NSTimeInterval) -> String{

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    return dateFormatter.stringFromDate(NSDate())
}



func getCreationTimeInt(dateString : String) -> String{

    let dateFormatter = NSDateFormatter()
    dateFormatter.locale = NSLocale.currentLocale()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    dateFormatter.timeZone = NSTimeZone.systemTimeZone()
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

    let time = dateFormatter.dateFromString(dateString)?.timeIntervalSince1970

    let distanceTime = NSDate().timeIntervalSince1970 - time!

    let stringTime = returnDistanceTime(distanceTime)

    print("**** The time \(stringTime)", terminator: "")

    return stringTime

}



getCreationTimeInt("2016-03-01 12:12:12")

enter image description here

在此处输入图片说明