0

I have two values like Todaytime 2017-10-30 15:31:51 and Expiretime 2017-10-31 10:02:17 --> string format like this, Now I subtract the Todaytime and Expiretime getting the answer, I will show on UIlabel with running time i.e., Reduces the Secounds like 23:59:29, 23:59:30...like that. I can reduces the time can you please any one help me. in iOS

how to subtract the Todaytime and Expiretime in iOS swift3 Todaytime 2017-10-30 15:31:51 Expiretime 2017-10-31 10:02:17

Mounica
  • 73
  • 9
  • I think this is a duplicate question. [https://stackoverflow.com/questions/27182023/getting-the-difference-between-two-nsdates-in-months-days-hours-minutes-seconds][1] – swetansh kumar Oct 30 '17 at 10:26
  • Note that in Swift property names and method names should start with lower case letters. (Classes and types should start with upper case letters.) This is a strong convention and one you should follow. – Duncan C Oct 30 '17 at 10:31

2 Answers2

1

let diff = Expiretime.timeIntervalSinceDate(Todaytime)

This will give you the difference as NSTimeInterval

Gurdev Singh
  • 1,996
  • 13
  • 11
  • hi Gurdev I put it but it's Shows the value of type String has no member in 'timeIntervalSinceDate' My Expiredate is in string format I converted into int or dounle the app will crash with reason optional value. – Mounica Oct 30 '17 at 10:30
  • If your variables are of String datatype then you need to convert them to NSDate first. Use NSDateFormatter & its method `dateFromString` to convert String data to NSDate. – Gurdev Singh Oct 30 '17 at 10:32
1

You could use timeIntervalSinceDate(), as in Gurdev's answer. That would give you a difference between the dates in seconds.

If you want the difference in calendar units, though, you should use the Calendar function dateComponents(_:from:to:). That would give you hours/minutes/seconds, days/hours/minutes, or whatever units you specify.

If you want to display the difference as a string, you should create a DateComponentsFormatter. That class has the function string(from:to:) which will build a formatted string directly from your 2 dates.

jamix
  • 5,484
  • 5
  • 26
  • 35
Duncan C
  • 128,072
  • 22
  • 173
  • 272