Assigning NSDateComponents to a label












-3















I'm creating a mobile app that has a countdown to a specific date. I think I have the timer itself correct, but I'm struggling to get it into a format where I can assign it to my label. I'm getting an error "Cannot invoke initializer for type 'String' with an argument list of type '(NSDateComponents)'. This error is found at the line "var date = String(openingGavelDate)". The outlet for the label has been properly created in this file.



First step I took was creating the date variable and setting it equal to the converted value of my other variable. Second step involved trying to look through documentation but so far I haven't really found any substantial documentation that can help.



func createGavelTimer() {
let openingGavelDate = NSDateComponents()
openingGavelDate.year = 2019
openingGavelDate.month = 7
openingGavelDate.day = 16
openingGavelDate.hour = 14
openingGavelDate.minute = 00
openingGavelDate.timeZone = NSTimeZone(abbreviation: "CST")! as TimeZone
var date = String(openingGavelDate) //problem is here
countdownLabel.text = date
}









share|improve this question



























    -3















    I'm creating a mobile app that has a countdown to a specific date. I think I have the timer itself correct, but I'm struggling to get it into a format where I can assign it to my label. I'm getting an error "Cannot invoke initializer for type 'String' with an argument list of type '(NSDateComponents)'. This error is found at the line "var date = String(openingGavelDate)". The outlet for the label has been properly created in this file.



    First step I took was creating the date variable and setting it equal to the converted value of my other variable. Second step involved trying to look through documentation but so far I haven't really found any substantial documentation that can help.



    func createGavelTimer() {
    let openingGavelDate = NSDateComponents()
    openingGavelDate.year = 2019
    openingGavelDate.month = 7
    openingGavelDate.day = 16
    openingGavelDate.hour = 14
    openingGavelDate.minute = 00
    openingGavelDate.timeZone = NSTimeZone(abbreviation: "CST")! as TimeZone
    var date = String(openingGavelDate) //problem is here
    countdownLabel.text = date
    }









    share|improve this question

























      -3












      -3








      -3








      I'm creating a mobile app that has a countdown to a specific date. I think I have the timer itself correct, but I'm struggling to get it into a format where I can assign it to my label. I'm getting an error "Cannot invoke initializer for type 'String' with an argument list of type '(NSDateComponents)'. This error is found at the line "var date = String(openingGavelDate)". The outlet for the label has been properly created in this file.



      First step I took was creating the date variable and setting it equal to the converted value of my other variable. Second step involved trying to look through documentation but so far I haven't really found any substantial documentation that can help.



      func createGavelTimer() {
      let openingGavelDate = NSDateComponents()
      openingGavelDate.year = 2019
      openingGavelDate.month = 7
      openingGavelDate.day = 16
      openingGavelDate.hour = 14
      openingGavelDate.minute = 00
      openingGavelDate.timeZone = NSTimeZone(abbreviation: "CST")! as TimeZone
      var date = String(openingGavelDate) //problem is here
      countdownLabel.text = date
      }









      share|improve this question














      I'm creating a mobile app that has a countdown to a specific date. I think I have the timer itself correct, but I'm struggling to get it into a format where I can assign it to my label. I'm getting an error "Cannot invoke initializer for type 'String' with an argument list of type '(NSDateComponents)'. This error is found at the line "var date = String(openingGavelDate)". The outlet for the label has been properly created in this file.



      First step I took was creating the date variable and setting it equal to the converted value of my other variable. Second step involved trying to look through documentation but so far I haven't really found any substantial documentation that can help.



      func createGavelTimer() {
      let openingGavelDate = NSDateComponents()
      openingGavelDate.year = 2019
      openingGavelDate.month = 7
      openingGavelDate.day = 16
      openingGavelDate.hour = 14
      openingGavelDate.minute = 00
      openingGavelDate.timeZone = NSTimeZone(abbreviation: "CST")! as TimeZone
      var date = String(openingGavelDate) //problem is here
      countdownLabel.text = date
      }






      swift






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 19 at 20:56









      Greg UctumGreg Uctum

      81




      81
























          3 Answers
          3






          active

          oldest

          votes


















          1














          One of possible solutions:



          let date = Calendar.current.date(from: openingGavelDate)

          let dateFormatter = DateFormatter()
          dateFormatter.timeStyle = .short
          dateFormatter.dateStyle = .medium
          dateFormatter.doesRelativeDateFormatting = true
          dateFormatter.timeZone = TimeZone(abbreviation: "CST")!


          let yourString = dateFormatter.string(from: date)





          share|improve this answer





















          • 1





            FYI - No need to set the formatter's timeZone to TimeZone.current since that is the default.

            – rmaddy
            Jan 19 at 22:25











          • @rmaddy thanks for the comment. This is just a sample. I will change it into question-like.

            – Vyacheslav
            Jan 19 at 22:27



















          0














          Try converting the NSDateComponents object to a Date by using Calendar.date(from:), and then converting that to a String using a DateFormatter:



          let gregorianCalendar = Calendar(identifier: .gregorian)

          if let date = gregorianCalendar.date(from: openingGavelDate as DateComponents) {
          let dateFormatter = DateFormatter()
          dateFormatter.dateStyle = .medium
          dateFormatter.timeStyle = .none

          countdownLabel.text = dateFormatter.string(from: date)
          }


          Also, as @Sh_Khan and @rmaddy have commented, you should be using DateComponents, TimeZone, etc. instead of their NS counterparts (unless you're using Swift 2 or lower).






          share|improve this answer





















          • 3





            Use DateFormatter do display dates. Don't just use default string conversion.

            – Sulthan
            Jan 19 at 21:07











          • @Sulthan Thanks for the suggestion, I forgot about DateFormatter. I'll update my answer.

            – Itai Steinherz
            Jan 19 at 21:10



















          0














          Two things you need to do to form your date:




          1. Set a calendar on the DateComponents instance.

          2. Get your date by accessing the date property on your DateComponents instance.


          Also, I'd recommend using time zone identifiers instead of abbreviation to specify a time zone; advantage is that identifiers will automatically apply special rules such as daylight savings as appropriate. (Below I've substituted the "America/Chicago" zone for UTC.)



          Try this code in a playground:



          var openingGavelDate = DateComponents()
          let timeZone = TimeZone(identifier: "America/Chicago")!
          openingGavelDate.year = 2019
          openingGavelDate.month = 7
          openingGavelDate.day = 16
          openingGavelDate.hour = 14
          openingGavelDate.minute = 00
          openingGavelDate.calendar = Calendar.current
          openingGavelDate.timeZone = timeZone
          let date = openingGavelDate.date
          print(date ?? "no date")


          Output: 2019-07-16 19:00:00 +0000 (your date in GMT.)



          This will get you a date, but notice that the Date class prints in GMT by default, because Date has no concept of timezone.



          To print date in the timezone and format you want, use DateFormatter:



          let f = DateFormatter()
          f.dateFormat = "yyyy-MM-dd hh:mm a"
          f.timeZone = TimeZone(identifier: "America/Chicago")!
          print(f.string(from: date!))


          Output: 2019-07-16 02:00 PM (your date & time, in CST and formatted for reading.)



          DateFormatter allows you to either control the format yourself, or follow the user's system settings to determine what is in the final string. See the docs for DateFormatter to see how to get it into the format you want to display.






          share|improve this answer





















          • 2





            Your date format is wrong. Never use YYYY. Use yyyy. And avoid specifying a fixed dateFormat. Use dateStyle and timeStyle whenever you show a date to a user so it is properly localized.

            – rmaddy
            Jan 19 at 21:29








          • 1





            It's also best to avoid creating timezones with an abbreviation. They are not unique. But why set the timezone at all? Why not show the date in local time?

            – rmaddy
            Jan 19 at 21:30











          • @rmaddy Date format string and timezone creation are updated.

            – jbelkins
            Jan 19 at 22:15











          • I leave it to the asker to determine how to format the date. I have presented dates both ways (exact format string or locale-based styles) depending on the context.

            – jbelkins
            Jan 19 at 22:17











          • No, you only show one way to format a Date. The print doesn't count since that is never a valid way to show a Date to a user.

            – rmaddy
            Jan 19 at 22:24











          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%2f54271327%2fassigning-nsdatecomponents-to-a-label%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          One of possible solutions:



          let date = Calendar.current.date(from: openingGavelDate)

          let dateFormatter = DateFormatter()
          dateFormatter.timeStyle = .short
          dateFormatter.dateStyle = .medium
          dateFormatter.doesRelativeDateFormatting = true
          dateFormatter.timeZone = TimeZone(abbreviation: "CST")!


          let yourString = dateFormatter.string(from: date)





          share|improve this answer





















          • 1





            FYI - No need to set the formatter's timeZone to TimeZone.current since that is the default.

            – rmaddy
            Jan 19 at 22:25











          • @rmaddy thanks for the comment. This is just a sample. I will change it into question-like.

            – Vyacheslav
            Jan 19 at 22:27
















          1














          One of possible solutions:



          let date = Calendar.current.date(from: openingGavelDate)

          let dateFormatter = DateFormatter()
          dateFormatter.timeStyle = .short
          dateFormatter.dateStyle = .medium
          dateFormatter.doesRelativeDateFormatting = true
          dateFormatter.timeZone = TimeZone(abbreviation: "CST")!


          let yourString = dateFormatter.string(from: date)





          share|improve this answer





















          • 1





            FYI - No need to set the formatter's timeZone to TimeZone.current since that is the default.

            – rmaddy
            Jan 19 at 22:25











          • @rmaddy thanks for the comment. This is just a sample. I will change it into question-like.

            – Vyacheslav
            Jan 19 at 22:27














          1












          1








          1







          One of possible solutions:



          let date = Calendar.current.date(from: openingGavelDate)

          let dateFormatter = DateFormatter()
          dateFormatter.timeStyle = .short
          dateFormatter.dateStyle = .medium
          dateFormatter.doesRelativeDateFormatting = true
          dateFormatter.timeZone = TimeZone(abbreviation: "CST")!


          let yourString = dateFormatter.string(from: date)





          share|improve this answer















          One of possible solutions:



          let date = Calendar.current.date(from: openingGavelDate)

          let dateFormatter = DateFormatter()
          dateFormatter.timeStyle = .short
          dateFormatter.dateStyle = .medium
          dateFormatter.doesRelativeDateFormatting = true
          dateFormatter.timeZone = TimeZone(abbreviation: "CST")!


          let yourString = dateFormatter.string(from: date)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 19 at 22:29

























          answered Jan 19 at 21:57









          VyacheslavVyacheslav

          14.1k962122




          14.1k962122








          • 1





            FYI - No need to set the formatter's timeZone to TimeZone.current since that is the default.

            – rmaddy
            Jan 19 at 22:25











          • @rmaddy thanks for the comment. This is just a sample. I will change it into question-like.

            – Vyacheslav
            Jan 19 at 22:27














          • 1





            FYI - No need to set the formatter's timeZone to TimeZone.current since that is the default.

            – rmaddy
            Jan 19 at 22:25











          • @rmaddy thanks for the comment. This is just a sample. I will change it into question-like.

            – Vyacheslav
            Jan 19 at 22:27








          1




          1





          FYI - No need to set the formatter's timeZone to TimeZone.current since that is the default.

          – rmaddy
          Jan 19 at 22:25





          FYI - No need to set the formatter's timeZone to TimeZone.current since that is the default.

          – rmaddy
          Jan 19 at 22:25













          @rmaddy thanks for the comment. This is just a sample. I will change it into question-like.

          – Vyacheslav
          Jan 19 at 22:27





          @rmaddy thanks for the comment. This is just a sample. I will change it into question-like.

          – Vyacheslav
          Jan 19 at 22:27













          0














          Try converting the NSDateComponents object to a Date by using Calendar.date(from:), and then converting that to a String using a DateFormatter:



          let gregorianCalendar = Calendar(identifier: .gregorian)

          if let date = gregorianCalendar.date(from: openingGavelDate as DateComponents) {
          let dateFormatter = DateFormatter()
          dateFormatter.dateStyle = .medium
          dateFormatter.timeStyle = .none

          countdownLabel.text = dateFormatter.string(from: date)
          }


          Also, as @Sh_Khan and @rmaddy have commented, you should be using DateComponents, TimeZone, etc. instead of their NS counterparts (unless you're using Swift 2 or lower).






          share|improve this answer





















          • 3





            Use DateFormatter do display dates. Don't just use default string conversion.

            – Sulthan
            Jan 19 at 21:07











          • @Sulthan Thanks for the suggestion, I forgot about DateFormatter. I'll update my answer.

            – Itai Steinherz
            Jan 19 at 21:10
















          0














          Try converting the NSDateComponents object to a Date by using Calendar.date(from:), and then converting that to a String using a DateFormatter:



          let gregorianCalendar = Calendar(identifier: .gregorian)

          if let date = gregorianCalendar.date(from: openingGavelDate as DateComponents) {
          let dateFormatter = DateFormatter()
          dateFormatter.dateStyle = .medium
          dateFormatter.timeStyle = .none

          countdownLabel.text = dateFormatter.string(from: date)
          }


          Also, as @Sh_Khan and @rmaddy have commented, you should be using DateComponents, TimeZone, etc. instead of their NS counterparts (unless you're using Swift 2 or lower).






          share|improve this answer





















          • 3





            Use DateFormatter do display dates. Don't just use default string conversion.

            – Sulthan
            Jan 19 at 21:07











          • @Sulthan Thanks for the suggestion, I forgot about DateFormatter. I'll update my answer.

            – Itai Steinherz
            Jan 19 at 21:10














          0












          0








          0







          Try converting the NSDateComponents object to a Date by using Calendar.date(from:), and then converting that to a String using a DateFormatter:



          let gregorianCalendar = Calendar(identifier: .gregorian)

          if let date = gregorianCalendar.date(from: openingGavelDate as DateComponents) {
          let dateFormatter = DateFormatter()
          dateFormatter.dateStyle = .medium
          dateFormatter.timeStyle = .none

          countdownLabel.text = dateFormatter.string(from: date)
          }


          Also, as @Sh_Khan and @rmaddy have commented, you should be using DateComponents, TimeZone, etc. instead of their NS counterparts (unless you're using Swift 2 or lower).






          share|improve this answer















          Try converting the NSDateComponents object to a Date by using Calendar.date(from:), and then converting that to a String using a DateFormatter:



          let gregorianCalendar = Calendar(identifier: .gregorian)

          if let date = gregorianCalendar.date(from: openingGavelDate as DateComponents) {
          let dateFormatter = DateFormatter()
          dateFormatter.dateStyle = .medium
          dateFormatter.timeStyle = .none

          countdownLabel.text = dateFormatter.string(from: date)
          }


          Also, as @Sh_Khan and @rmaddy have commented, you should be using DateComponents, TimeZone, etc. instead of their NS counterparts (unless you're using Swift 2 or lower).







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 19 at 21:17

























          answered Jan 19 at 20:59









          Itai SteinherzItai Steinherz

          43529




          43529








          • 3





            Use DateFormatter do display dates. Don't just use default string conversion.

            – Sulthan
            Jan 19 at 21:07











          • @Sulthan Thanks for the suggestion, I forgot about DateFormatter. I'll update my answer.

            – Itai Steinherz
            Jan 19 at 21:10














          • 3





            Use DateFormatter do display dates. Don't just use default string conversion.

            – Sulthan
            Jan 19 at 21:07











          • @Sulthan Thanks for the suggestion, I forgot about DateFormatter. I'll update my answer.

            – Itai Steinherz
            Jan 19 at 21:10








          3




          3





          Use DateFormatter do display dates. Don't just use default string conversion.

          – Sulthan
          Jan 19 at 21:07





          Use DateFormatter do display dates. Don't just use default string conversion.

          – Sulthan
          Jan 19 at 21:07













          @Sulthan Thanks for the suggestion, I forgot about DateFormatter. I'll update my answer.

          – Itai Steinherz
          Jan 19 at 21:10





          @Sulthan Thanks for the suggestion, I forgot about DateFormatter. I'll update my answer.

          – Itai Steinherz
          Jan 19 at 21:10











          0














          Two things you need to do to form your date:




          1. Set a calendar on the DateComponents instance.

          2. Get your date by accessing the date property on your DateComponents instance.


          Also, I'd recommend using time zone identifiers instead of abbreviation to specify a time zone; advantage is that identifiers will automatically apply special rules such as daylight savings as appropriate. (Below I've substituted the "America/Chicago" zone for UTC.)



          Try this code in a playground:



          var openingGavelDate = DateComponents()
          let timeZone = TimeZone(identifier: "America/Chicago")!
          openingGavelDate.year = 2019
          openingGavelDate.month = 7
          openingGavelDate.day = 16
          openingGavelDate.hour = 14
          openingGavelDate.minute = 00
          openingGavelDate.calendar = Calendar.current
          openingGavelDate.timeZone = timeZone
          let date = openingGavelDate.date
          print(date ?? "no date")


          Output: 2019-07-16 19:00:00 +0000 (your date in GMT.)



          This will get you a date, but notice that the Date class prints in GMT by default, because Date has no concept of timezone.



          To print date in the timezone and format you want, use DateFormatter:



          let f = DateFormatter()
          f.dateFormat = "yyyy-MM-dd hh:mm a"
          f.timeZone = TimeZone(identifier: "America/Chicago")!
          print(f.string(from: date!))


          Output: 2019-07-16 02:00 PM (your date & time, in CST and formatted for reading.)



          DateFormatter allows you to either control the format yourself, or follow the user's system settings to determine what is in the final string. See the docs for DateFormatter to see how to get it into the format you want to display.






          share|improve this answer





















          • 2





            Your date format is wrong. Never use YYYY. Use yyyy. And avoid specifying a fixed dateFormat. Use dateStyle and timeStyle whenever you show a date to a user so it is properly localized.

            – rmaddy
            Jan 19 at 21:29








          • 1





            It's also best to avoid creating timezones with an abbreviation. They are not unique. But why set the timezone at all? Why not show the date in local time?

            – rmaddy
            Jan 19 at 21:30











          • @rmaddy Date format string and timezone creation are updated.

            – jbelkins
            Jan 19 at 22:15











          • I leave it to the asker to determine how to format the date. I have presented dates both ways (exact format string or locale-based styles) depending on the context.

            – jbelkins
            Jan 19 at 22:17











          • No, you only show one way to format a Date. The print doesn't count since that is never a valid way to show a Date to a user.

            – rmaddy
            Jan 19 at 22:24
















          0














          Two things you need to do to form your date:




          1. Set a calendar on the DateComponents instance.

          2. Get your date by accessing the date property on your DateComponents instance.


          Also, I'd recommend using time zone identifiers instead of abbreviation to specify a time zone; advantage is that identifiers will automatically apply special rules such as daylight savings as appropriate. (Below I've substituted the "America/Chicago" zone for UTC.)



          Try this code in a playground:



          var openingGavelDate = DateComponents()
          let timeZone = TimeZone(identifier: "America/Chicago")!
          openingGavelDate.year = 2019
          openingGavelDate.month = 7
          openingGavelDate.day = 16
          openingGavelDate.hour = 14
          openingGavelDate.minute = 00
          openingGavelDate.calendar = Calendar.current
          openingGavelDate.timeZone = timeZone
          let date = openingGavelDate.date
          print(date ?? "no date")


          Output: 2019-07-16 19:00:00 +0000 (your date in GMT.)



          This will get you a date, but notice that the Date class prints in GMT by default, because Date has no concept of timezone.



          To print date in the timezone and format you want, use DateFormatter:



          let f = DateFormatter()
          f.dateFormat = "yyyy-MM-dd hh:mm a"
          f.timeZone = TimeZone(identifier: "America/Chicago")!
          print(f.string(from: date!))


          Output: 2019-07-16 02:00 PM (your date & time, in CST and formatted for reading.)



          DateFormatter allows you to either control the format yourself, or follow the user's system settings to determine what is in the final string. See the docs for DateFormatter to see how to get it into the format you want to display.






          share|improve this answer





















          • 2





            Your date format is wrong. Never use YYYY. Use yyyy. And avoid specifying a fixed dateFormat. Use dateStyle and timeStyle whenever you show a date to a user so it is properly localized.

            – rmaddy
            Jan 19 at 21:29








          • 1





            It's also best to avoid creating timezones with an abbreviation. They are not unique. But why set the timezone at all? Why not show the date in local time?

            – rmaddy
            Jan 19 at 21:30











          • @rmaddy Date format string and timezone creation are updated.

            – jbelkins
            Jan 19 at 22:15











          • I leave it to the asker to determine how to format the date. I have presented dates both ways (exact format string or locale-based styles) depending on the context.

            – jbelkins
            Jan 19 at 22:17











          • No, you only show one way to format a Date. The print doesn't count since that is never a valid way to show a Date to a user.

            – rmaddy
            Jan 19 at 22:24














          0












          0








          0







          Two things you need to do to form your date:




          1. Set a calendar on the DateComponents instance.

          2. Get your date by accessing the date property on your DateComponents instance.


          Also, I'd recommend using time zone identifiers instead of abbreviation to specify a time zone; advantage is that identifiers will automatically apply special rules such as daylight savings as appropriate. (Below I've substituted the "America/Chicago" zone for UTC.)



          Try this code in a playground:



          var openingGavelDate = DateComponents()
          let timeZone = TimeZone(identifier: "America/Chicago")!
          openingGavelDate.year = 2019
          openingGavelDate.month = 7
          openingGavelDate.day = 16
          openingGavelDate.hour = 14
          openingGavelDate.minute = 00
          openingGavelDate.calendar = Calendar.current
          openingGavelDate.timeZone = timeZone
          let date = openingGavelDate.date
          print(date ?? "no date")


          Output: 2019-07-16 19:00:00 +0000 (your date in GMT.)



          This will get you a date, but notice that the Date class prints in GMT by default, because Date has no concept of timezone.



          To print date in the timezone and format you want, use DateFormatter:



          let f = DateFormatter()
          f.dateFormat = "yyyy-MM-dd hh:mm a"
          f.timeZone = TimeZone(identifier: "America/Chicago")!
          print(f.string(from: date!))


          Output: 2019-07-16 02:00 PM (your date & time, in CST and formatted for reading.)



          DateFormatter allows you to either control the format yourself, or follow the user's system settings to determine what is in the final string. See the docs for DateFormatter to see how to get it into the format you want to display.






          share|improve this answer















          Two things you need to do to form your date:




          1. Set a calendar on the DateComponents instance.

          2. Get your date by accessing the date property on your DateComponents instance.


          Also, I'd recommend using time zone identifiers instead of abbreviation to specify a time zone; advantage is that identifiers will automatically apply special rules such as daylight savings as appropriate. (Below I've substituted the "America/Chicago" zone for UTC.)



          Try this code in a playground:



          var openingGavelDate = DateComponents()
          let timeZone = TimeZone(identifier: "America/Chicago")!
          openingGavelDate.year = 2019
          openingGavelDate.month = 7
          openingGavelDate.day = 16
          openingGavelDate.hour = 14
          openingGavelDate.minute = 00
          openingGavelDate.calendar = Calendar.current
          openingGavelDate.timeZone = timeZone
          let date = openingGavelDate.date
          print(date ?? "no date")


          Output: 2019-07-16 19:00:00 +0000 (your date in GMT.)



          This will get you a date, but notice that the Date class prints in GMT by default, because Date has no concept of timezone.



          To print date in the timezone and format you want, use DateFormatter:



          let f = DateFormatter()
          f.dateFormat = "yyyy-MM-dd hh:mm a"
          f.timeZone = TimeZone(identifier: "America/Chicago")!
          print(f.string(from: date!))


          Output: 2019-07-16 02:00 PM (your date & time, in CST and formatted for reading.)



          DateFormatter allows you to either control the format yourself, or follow the user's system settings to determine what is in the final string. See the docs for DateFormatter to see how to get it into the format you want to display.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 19 at 22:14

























          answered Jan 19 at 21:27









          jbelkinsjbelkins

          17512




          17512








          • 2





            Your date format is wrong. Never use YYYY. Use yyyy. And avoid specifying a fixed dateFormat. Use dateStyle and timeStyle whenever you show a date to a user so it is properly localized.

            – rmaddy
            Jan 19 at 21:29








          • 1





            It's also best to avoid creating timezones with an abbreviation. They are not unique. But why set the timezone at all? Why not show the date in local time?

            – rmaddy
            Jan 19 at 21:30











          • @rmaddy Date format string and timezone creation are updated.

            – jbelkins
            Jan 19 at 22:15











          • I leave it to the asker to determine how to format the date. I have presented dates both ways (exact format string or locale-based styles) depending on the context.

            – jbelkins
            Jan 19 at 22:17











          • No, you only show one way to format a Date. The print doesn't count since that is never a valid way to show a Date to a user.

            – rmaddy
            Jan 19 at 22:24














          • 2





            Your date format is wrong. Never use YYYY. Use yyyy. And avoid specifying a fixed dateFormat. Use dateStyle and timeStyle whenever you show a date to a user so it is properly localized.

            – rmaddy
            Jan 19 at 21:29








          • 1





            It's also best to avoid creating timezones with an abbreviation. They are not unique. But why set the timezone at all? Why not show the date in local time?

            – rmaddy
            Jan 19 at 21:30











          • @rmaddy Date format string and timezone creation are updated.

            – jbelkins
            Jan 19 at 22:15











          • I leave it to the asker to determine how to format the date. I have presented dates both ways (exact format string or locale-based styles) depending on the context.

            – jbelkins
            Jan 19 at 22:17











          • No, you only show one way to format a Date. The print doesn't count since that is never a valid way to show a Date to a user.

            – rmaddy
            Jan 19 at 22:24








          2




          2





          Your date format is wrong. Never use YYYY. Use yyyy. And avoid specifying a fixed dateFormat. Use dateStyle and timeStyle whenever you show a date to a user so it is properly localized.

          – rmaddy
          Jan 19 at 21:29







          Your date format is wrong. Never use YYYY. Use yyyy. And avoid specifying a fixed dateFormat. Use dateStyle and timeStyle whenever you show a date to a user so it is properly localized.

          – rmaddy
          Jan 19 at 21:29






          1




          1





          It's also best to avoid creating timezones with an abbreviation. They are not unique. But why set the timezone at all? Why not show the date in local time?

          – rmaddy
          Jan 19 at 21:30





          It's also best to avoid creating timezones with an abbreviation. They are not unique. But why set the timezone at all? Why not show the date in local time?

          – rmaddy
          Jan 19 at 21:30













          @rmaddy Date format string and timezone creation are updated.

          – jbelkins
          Jan 19 at 22:15





          @rmaddy Date format string and timezone creation are updated.

          – jbelkins
          Jan 19 at 22:15













          I leave it to the asker to determine how to format the date. I have presented dates both ways (exact format string or locale-based styles) depending on the context.

          – jbelkins
          Jan 19 at 22:17





          I leave it to the asker to determine how to format the date. I have presented dates both ways (exact format string or locale-based styles) depending on the context.

          – jbelkins
          Jan 19 at 22:17













          No, you only show one way to format a Date. The print doesn't count since that is never a valid way to show a Date to a user.

          – rmaddy
          Jan 19 at 22:24





          No, you only show one way to format a Date. The print doesn't count since that is never a valid way to show a Date to a user.

          – rmaddy
          Jan 19 at 22:24


















          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%2f54271327%2fassigning-nsdatecomponents-to-a-label%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

          Liquibase includeAll doesn't find base path

          How to use setInterval in EJS file?

          Petrus Granier-Deferre