Difference between boarding time and current time in UTC in iOS , Swift












0















I am getting Boarding Time from service ( lets say BT- Boarding Time)
I need to find out the differnce between Boarding Time and current time and then find out the difference in Hour , Min.



The condition is user may check the difference between these from any country in the world. so i used UTC to calculate but its giving correct result , kindly help me in this.



 func dayStringFromTime() -> String {
let currentTimeUnix = Date().timeIntervalSince1970
let date = NSDate(timeIntervalSince1970: currentTimeUnix)
let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "HH:mm:ss"
return date.description
}

let CT = dayStringFromTime() //time1
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd HH:mm:ss"
let CTDate = formatter.date(from: CT)
let time1 = boardingDateTime//timeformatter.date(from: CT)
let time2 = CT_Date//timeformatter.date(from: ETD)
//You can directly use from here if you have two dates
let interval = time1.timeIntervalSince(time2! as Date)
let hour = (interval ) / 3600;
let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
let intervalInt = Int(interval)
print("(intervalInt < 0 ? "-" : "+") (Int(hour)) Hours (Int(Int(minute))) Minutes")
let minText = Int(minute) > 0 && Int(minute) != 0 ? " (Int(minute)) min" : (Int(minute) < 0 ? " (Int(abs(minute))) min" : "")
let hrText = Int(hour) > 0 && Int(hour) != 0 ? " (Int(hour)) hr" : (Int(hour) < 0 ? " (Int(abs(hour))) hr" : "")


this url https://stackoverflow.com/a/28608779/3400991 shows the exact problem about this result, kindly help










share|improve this question


















  • 1





    What version of Swift are you working in?

    – Daniel T.
    Nov 25 '18 at 20:54











  • i am using Swift 4

    – Shobhakar Tiwari
    Nov 25 '18 at 20:57






  • 1





    Take a look at DateComponentsFormatter to get rid of the weird date math.

    – vadian
    Nov 25 '18 at 20:59











  • @DanielT.'s answer will get you the right result IF you have formatted your boarding time correctly. Can you provide the code where you format it? Do you provide it with the correct TimeZone?

    – fguchelaar
    Nov 25 '18 at 22:13






  • 1





    @fguchelaar There's no formatting a Date object. As long as he created it properly (presumably from a network response?) my answer will work. I like @MadProgrammer's reference to DateComponentsFormatter though.

    – Daniel T.
    Nov 25 '18 at 22:18
















0















I am getting Boarding Time from service ( lets say BT- Boarding Time)
I need to find out the differnce between Boarding Time and current time and then find out the difference in Hour , Min.



The condition is user may check the difference between these from any country in the world. so i used UTC to calculate but its giving correct result , kindly help me in this.



 func dayStringFromTime() -> String {
let currentTimeUnix = Date().timeIntervalSince1970
let date = NSDate(timeIntervalSince1970: currentTimeUnix)
let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "HH:mm:ss"
return date.description
}

let CT = dayStringFromTime() //time1
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd HH:mm:ss"
let CTDate = formatter.date(from: CT)
let time1 = boardingDateTime//timeformatter.date(from: CT)
let time2 = CT_Date//timeformatter.date(from: ETD)
//You can directly use from here if you have two dates
let interval = time1.timeIntervalSince(time2! as Date)
let hour = (interval ) / 3600;
let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
let intervalInt = Int(interval)
print("(intervalInt < 0 ? "-" : "+") (Int(hour)) Hours (Int(Int(minute))) Minutes")
let minText = Int(minute) > 0 && Int(minute) != 0 ? " (Int(minute)) min" : (Int(minute) < 0 ? " (Int(abs(minute))) min" : "")
let hrText = Int(hour) > 0 && Int(hour) != 0 ? " (Int(hour)) hr" : (Int(hour) < 0 ? " (Int(abs(hour))) hr" : "")


this url https://stackoverflow.com/a/28608779/3400991 shows the exact problem about this result, kindly help










share|improve this question


















  • 1





    What version of Swift are you working in?

    – Daniel T.
    Nov 25 '18 at 20:54











  • i am using Swift 4

    – Shobhakar Tiwari
    Nov 25 '18 at 20:57






  • 1





    Take a look at DateComponentsFormatter to get rid of the weird date math.

    – vadian
    Nov 25 '18 at 20:59











  • @DanielT.'s answer will get you the right result IF you have formatted your boarding time correctly. Can you provide the code where you format it? Do you provide it with the correct TimeZone?

    – fguchelaar
    Nov 25 '18 at 22:13






  • 1





    @fguchelaar There's no formatting a Date object. As long as he created it properly (presumably from a network response?) my answer will work. I like @MadProgrammer's reference to DateComponentsFormatter though.

    – Daniel T.
    Nov 25 '18 at 22:18














0












0








0


1






I am getting Boarding Time from service ( lets say BT- Boarding Time)
I need to find out the differnce between Boarding Time and current time and then find out the difference in Hour , Min.



The condition is user may check the difference between these from any country in the world. so i used UTC to calculate but its giving correct result , kindly help me in this.



 func dayStringFromTime() -> String {
let currentTimeUnix = Date().timeIntervalSince1970
let date = NSDate(timeIntervalSince1970: currentTimeUnix)
let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "HH:mm:ss"
return date.description
}

let CT = dayStringFromTime() //time1
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd HH:mm:ss"
let CTDate = formatter.date(from: CT)
let time1 = boardingDateTime//timeformatter.date(from: CT)
let time2 = CT_Date//timeformatter.date(from: ETD)
//You can directly use from here if you have two dates
let interval = time1.timeIntervalSince(time2! as Date)
let hour = (interval ) / 3600;
let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
let intervalInt = Int(interval)
print("(intervalInt < 0 ? "-" : "+") (Int(hour)) Hours (Int(Int(minute))) Minutes")
let minText = Int(minute) > 0 && Int(minute) != 0 ? " (Int(minute)) min" : (Int(minute) < 0 ? " (Int(abs(minute))) min" : "")
let hrText = Int(hour) > 0 && Int(hour) != 0 ? " (Int(hour)) hr" : (Int(hour) < 0 ? " (Int(abs(hour))) hr" : "")


this url https://stackoverflow.com/a/28608779/3400991 shows the exact problem about this result, kindly help










share|improve this question














I am getting Boarding Time from service ( lets say BT- Boarding Time)
I need to find out the differnce between Boarding Time and current time and then find out the difference in Hour , Min.



The condition is user may check the difference between these from any country in the world. so i used UTC to calculate but its giving correct result , kindly help me in this.



 func dayStringFromTime() -> String {
let currentTimeUnix = Date().timeIntervalSince1970
let date = NSDate(timeIntervalSince1970: currentTimeUnix)
let dateFormatter = DateFormatter()
// dateFormatter.dateFormat = "HH:mm:ss"
return date.description
}

let CT = dayStringFromTime() //time1
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd HH:mm:ss"
let CTDate = formatter.date(from: CT)
let time1 = boardingDateTime//timeformatter.date(from: CT)
let time2 = CT_Date//timeformatter.date(from: ETD)
//You can directly use from here if you have two dates
let interval = time1.timeIntervalSince(time2! as Date)
let hour = (interval ) / 3600;
let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
let intervalInt = Int(interval)
print("(intervalInt < 0 ? "-" : "+") (Int(hour)) Hours (Int(Int(minute))) Minutes")
let minText = Int(minute) > 0 && Int(minute) != 0 ? " (Int(minute)) min" : (Int(minute) < 0 ? " (Int(abs(minute))) min" : "")
let hrText = Int(hour) > 0 && Int(hour) != 0 ? " (Int(hour)) hr" : (Int(hour) < 0 ? " (Int(abs(hour))) hr" : "")


this url https://stackoverflow.com/a/28608779/3400991 shows the exact problem about this result, kindly help







ios swift dateformatter






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 25 '18 at 20:50









Shobhakar TiwariShobhakar Tiwari

5,0682358




5,0682358








  • 1





    What version of Swift are you working in?

    – Daniel T.
    Nov 25 '18 at 20:54











  • i am using Swift 4

    – Shobhakar Tiwari
    Nov 25 '18 at 20:57






  • 1





    Take a look at DateComponentsFormatter to get rid of the weird date math.

    – vadian
    Nov 25 '18 at 20:59











  • @DanielT.'s answer will get you the right result IF you have formatted your boarding time correctly. Can you provide the code where you format it? Do you provide it with the correct TimeZone?

    – fguchelaar
    Nov 25 '18 at 22:13






  • 1





    @fguchelaar There's no formatting a Date object. As long as he created it properly (presumably from a network response?) my answer will work. I like @MadProgrammer's reference to DateComponentsFormatter though.

    – Daniel T.
    Nov 25 '18 at 22:18














  • 1





    What version of Swift are you working in?

    – Daniel T.
    Nov 25 '18 at 20:54











  • i am using Swift 4

    – Shobhakar Tiwari
    Nov 25 '18 at 20:57






  • 1





    Take a look at DateComponentsFormatter to get rid of the weird date math.

    – vadian
    Nov 25 '18 at 20:59











  • @DanielT.'s answer will get you the right result IF you have formatted your boarding time correctly. Can you provide the code where you format it? Do you provide it with the correct TimeZone?

    – fguchelaar
    Nov 25 '18 at 22:13






  • 1





    @fguchelaar There's no formatting a Date object. As long as he created it properly (presumably from a network response?) my answer will work. I like @MadProgrammer's reference to DateComponentsFormatter though.

    – Daniel T.
    Nov 25 '18 at 22:18








1




1





What version of Swift are you working in?

– Daniel T.
Nov 25 '18 at 20:54





What version of Swift are you working in?

– Daniel T.
Nov 25 '18 at 20:54













i am using Swift 4

– Shobhakar Tiwari
Nov 25 '18 at 20:57





i am using Swift 4

– Shobhakar Tiwari
Nov 25 '18 at 20:57




1




1





Take a look at DateComponentsFormatter to get rid of the weird date math.

– vadian
Nov 25 '18 at 20:59





Take a look at DateComponentsFormatter to get rid of the weird date math.

– vadian
Nov 25 '18 at 20:59













@DanielT.'s answer will get you the right result IF you have formatted your boarding time correctly. Can you provide the code where you format it? Do you provide it with the correct TimeZone?

– fguchelaar
Nov 25 '18 at 22:13





@DanielT.'s answer will get you the right result IF you have formatted your boarding time correctly. Can you provide the code where you format it? Do you provide it with the correct TimeZone?

– fguchelaar
Nov 25 '18 at 22:13




1




1





@fguchelaar There's no formatting a Date object. As long as he created it properly (presumably from a network response?) my answer will work. I like @MadProgrammer's reference to DateComponentsFormatter though.

– Daniel T.
Nov 25 '18 at 22:18





@fguchelaar There's no formatting a Date object. As long as he created it properly (presumably from a network response?) my answer will work. I like @MadProgrammer's reference to DateComponentsFormatter though.

– Daniel T.
Nov 25 '18 at 22:18












2 Answers
2






active

oldest

votes


















2














This is way easier that you have made it out to be:



let boardingTime = Date().addingTimeInterval(3200) // the `addingTimeInterval` is for demonstration purposes only.
let now = Date()
let difference = Calendar.current.dateComponents([.hour, .minute, .second], from: now, to: boardingTime)
print("Boarding will be in: (difference.hour!):(difference.minute!):(difference.second!)")





share|improve this answer

































    1














    First of all, be very careful with date/time mathematics, it's not a straight linear conversion, there are lots and lots of rules which go around it and make it ... complicated.



    The first thing you need is to calculate the difference between the two times, lucky for you, this is relatively easy...



    var boardingTime = Date()
    boardingTime = bordingTime.addingTimeInterval(Double.random(in: 0.0..<86400.0))
    let now = Date()
    let difference = boardingTime.timeIntervalSince(now)


    This gives you the number of seconds between these two values (a positive value been the time till, a negative value been the time after)



    Next, you need the hours/minutes in some form of human readable notation. It might seem tempting to just start by multiplying and dividing everything by 60, but that would be a mistake and lead you into bad habits (sure over a short range it's not bad, but you need to be very careful)



    A better solution would be to use a DateComponentsFormatter...



    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute]
    formatter.unitsStyle = .abbreviated

    formatter.string(from: difference)


    Which will take care of all the "rules" for you, but, it will also localise the results, always a bonus.



    The above example will print something like...



    10h 28m





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471839%2fdifference-between-boarding-time-and-current-time-in-utc-in-ios-swift%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      This is way easier that you have made it out to be:



      let boardingTime = Date().addingTimeInterval(3200) // the `addingTimeInterval` is for demonstration purposes only.
      let now = Date()
      let difference = Calendar.current.dateComponents([.hour, .minute, .second], from: now, to: boardingTime)
      print("Boarding will be in: (difference.hour!):(difference.minute!):(difference.second!)")





      share|improve this answer






























        2














        This is way easier that you have made it out to be:



        let boardingTime = Date().addingTimeInterval(3200) // the `addingTimeInterval` is for demonstration purposes only.
        let now = Date()
        let difference = Calendar.current.dateComponents([.hour, .minute, .second], from: now, to: boardingTime)
        print("Boarding will be in: (difference.hour!):(difference.minute!):(difference.second!)")





        share|improve this answer




























          2












          2








          2







          This is way easier that you have made it out to be:



          let boardingTime = Date().addingTimeInterval(3200) // the `addingTimeInterval` is for demonstration purposes only.
          let now = Date()
          let difference = Calendar.current.dateComponents([.hour, .minute, .second], from: now, to: boardingTime)
          print("Boarding will be in: (difference.hour!):(difference.minute!):(difference.second!)")





          share|improve this answer















          This is way easier that you have made it out to be:



          let boardingTime = Date().addingTimeInterval(3200) // the `addingTimeInterval` is for demonstration purposes only.
          let now = Date()
          let difference = Calendar.current.dateComponents([.hour, .minute, .second], from: now, to: boardingTime)
          print("Boarding will be in: (difference.hour!):(difference.minute!):(difference.second!)")






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 25 '18 at 21:36

























          answered Nov 25 '18 at 21:21









          Daniel T.Daniel T.

          14.2k22734




          14.2k22734

























              1














              First of all, be very careful with date/time mathematics, it's not a straight linear conversion, there are lots and lots of rules which go around it and make it ... complicated.



              The first thing you need is to calculate the difference between the two times, lucky for you, this is relatively easy...



              var boardingTime = Date()
              boardingTime = bordingTime.addingTimeInterval(Double.random(in: 0.0..<86400.0))
              let now = Date()
              let difference = boardingTime.timeIntervalSince(now)


              This gives you the number of seconds between these two values (a positive value been the time till, a negative value been the time after)



              Next, you need the hours/minutes in some form of human readable notation. It might seem tempting to just start by multiplying and dividing everything by 60, but that would be a mistake and lead you into bad habits (sure over a short range it's not bad, but you need to be very careful)



              A better solution would be to use a DateComponentsFormatter...



              let formatter = DateComponentsFormatter()
              formatter.allowedUnits = [.hour, .minute]
              formatter.unitsStyle = .abbreviated

              formatter.string(from: difference)


              Which will take care of all the "rules" for you, but, it will also localise the results, always a bonus.



              The above example will print something like...



              10h 28m





              share|improve this answer




























                1














                First of all, be very careful with date/time mathematics, it's not a straight linear conversion, there are lots and lots of rules which go around it and make it ... complicated.



                The first thing you need is to calculate the difference between the two times, lucky for you, this is relatively easy...



                var boardingTime = Date()
                boardingTime = bordingTime.addingTimeInterval(Double.random(in: 0.0..<86400.0))
                let now = Date()
                let difference = boardingTime.timeIntervalSince(now)


                This gives you the number of seconds between these two values (a positive value been the time till, a negative value been the time after)



                Next, you need the hours/minutes in some form of human readable notation. It might seem tempting to just start by multiplying and dividing everything by 60, but that would be a mistake and lead you into bad habits (sure over a short range it's not bad, but you need to be very careful)



                A better solution would be to use a DateComponentsFormatter...



                let formatter = DateComponentsFormatter()
                formatter.allowedUnits = [.hour, .minute]
                formatter.unitsStyle = .abbreviated

                formatter.string(from: difference)


                Which will take care of all the "rules" for you, but, it will also localise the results, always a bonus.



                The above example will print something like...



                10h 28m





                share|improve this answer


























                  1












                  1








                  1







                  First of all, be very careful with date/time mathematics, it's not a straight linear conversion, there are lots and lots of rules which go around it and make it ... complicated.



                  The first thing you need is to calculate the difference between the two times, lucky for you, this is relatively easy...



                  var boardingTime = Date()
                  boardingTime = bordingTime.addingTimeInterval(Double.random(in: 0.0..<86400.0))
                  let now = Date()
                  let difference = boardingTime.timeIntervalSince(now)


                  This gives you the number of seconds between these two values (a positive value been the time till, a negative value been the time after)



                  Next, you need the hours/minutes in some form of human readable notation. It might seem tempting to just start by multiplying and dividing everything by 60, but that would be a mistake and lead you into bad habits (sure over a short range it's not bad, but you need to be very careful)



                  A better solution would be to use a DateComponentsFormatter...



                  let formatter = DateComponentsFormatter()
                  formatter.allowedUnits = [.hour, .minute]
                  formatter.unitsStyle = .abbreviated

                  formatter.string(from: difference)


                  Which will take care of all the "rules" for you, but, it will also localise the results, always a bonus.



                  The above example will print something like...



                  10h 28m





                  share|improve this answer













                  First of all, be very careful with date/time mathematics, it's not a straight linear conversion, there are lots and lots of rules which go around it and make it ... complicated.



                  The first thing you need is to calculate the difference between the two times, lucky for you, this is relatively easy...



                  var boardingTime = Date()
                  boardingTime = bordingTime.addingTimeInterval(Double.random(in: 0.0..<86400.0))
                  let now = Date()
                  let difference = boardingTime.timeIntervalSince(now)


                  This gives you the number of seconds between these two values (a positive value been the time till, a negative value been the time after)



                  Next, you need the hours/minutes in some form of human readable notation. It might seem tempting to just start by multiplying and dividing everything by 60, but that would be a mistake and lead you into bad habits (sure over a short range it's not bad, but you need to be very careful)



                  A better solution would be to use a DateComponentsFormatter...



                  let formatter = DateComponentsFormatter()
                  formatter.allowedUnits = [.hour, .minute]
                  formatter.unitsStyle = .abbreviated

                  formatter.string(from: difference)


                  Which will take care of all the "rules" for you, but, it will also localise the results, always a bonus.



                  The above example will print something like...



                  10h 28m






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 25 '18 at 21:22









                  MadProgrammerMadProgrammer

                  301k17155270




                  301k17155270






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471839%2fdifference-between-boarding-time-and-current-time-in-utc-in-ios-swift%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      Refactoring coordinates for Minecraft Pi buildings written in Python