Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

nsdate - How to get system time in formatted style swift?

I have such time which I have to send to the server:

2019-03-06T14:49:55+01:00

I thought that I can do it in such way:

NSDate(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970))

but I got such time:

2021-01-24 15:42:31 +0000

I thought that I have to user decoding pattern, so used such way:

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss+z"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
        
let time = NSDate(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970))

if let date = dateFormatterGet.date(from: time.description) {
   print(dateFormatterPrint.string(from: date))
} else {
   print("There was an error decoding the string")
}

but its output was:

There was an error decoding the string

what means that I can't decode this time in such way. What I did wrong?

question from:https://stackoverflow.com/questions/65872644/how-to-get-system-time-in-formatted-style-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are creating a string from a date from a time interval from a date, three of the conversions are waste.

The conversion failed because time.description doesn't match the format yyyy-MM-dd HH:mm:ss+z

To get an ISO8601 string with time zone the date format is yyyy-MM-dd'T'HH:mm:ssZ and you have to specify a fixed locale

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let isoString = formatter.string(from: Date())

There is a shorter way as suggested by Rob in the comments

let formatter = ISO8601DateFormatter()
formatter.timeZone = .current
let isoString = formatter.string(from: Date())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...