Lalit kumar
Lalit kumar

Reputation: 2207

Timestamp doesn't change in string format

let dateFormater : DateFormatter = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormater.date(from: "2016-11-11T11:42:27Z")
print("date is  ---->%@",date)

let timestamp = date?.timeIntervalSince1970
print("timestamp is  ---->%@",timestamp!)

let str =  String(format: "%@",timestamp!)
print("str value is ---->%@",str)

date is -----> 2016-11-11 11:42:27 +000
timestamp is----->1478864547.0
str value is-----> null

Getting date and time stamp value. How to change timestamp value into string. Means 1478864547.0(timestampvalue) to string formate

let str = String(format: "%@",timestamp!) whats wrong this line.

Upvotes: 1

Views: 129

Answers (3)

Hitesh Surani
Hitesh Surani

Reputation: 13557

You are getting null value. timestamp is not a String value so you can no get a String value directly, You have to use Float to String Casting Do as follow I am sure it will work for you.

let dateFormater : DateFormatter = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormater.date(from: "2016-11-11T11:42:27Z")
print("date is  ---->%@",date)

let timestamp = date?.timeIntervalSince1970
print("timestamp is  ---->%@",timestamp!)

let str =  String(format: "%0.0f",timestamp!)
print("str value is ---->%@",str)

TimeInterval is typealias for Double, So use or " 0.0f " " %lf ".

Upvotes: 0

ganzogo
ganzogo

Reputation: 2614

The problem is that timestamp is not an object - it's a TimeInterval (which is just a typealias for Double). If you want to use a formatted string, you need to do "%lf".

Upvotes: 1

Nirav D
Nirav D

Reputation: 72440

You can simply use let timestampInString = "\(timestamp)".

If it is optional then

if let timestamp = date?.timeIntervalSince1970 {
     let timestampInString = "\(timestamp)"
}

Upvotes: 1

Related Questions