skip to Main Content

I have a time coming from service in string form like so "12:30 PM".

I am able to get this time but I want to add this time in current date. like so

31/3/2021 12:30 PM 

The current date is in date object and coming time is in string format.

Please let me know what is a right way to do so? I am right now taking 12, 30,from string and setting it via Calendar. But dont know how to set am pm . Please let me know how to append time with date object. Thanks in advance.

2

Answers


  1. First, if that is the date string you are getting from your service, it is incomplete. It needs a time zone.

    Here’s what I would do:

    1. Assuming the service always uses the same time zone, find out that time zone.

    2. Create a date formatter for that date string format, including the AM/PM bit.

    3. Set the date formatter to use the time zone from step 1.

    4. Convert the date string to a Date object using your DateFormatter.

    5. Use the current calendar to extract the hours and minutes values into a DateComponents object.

    6. Get the current date, and use the Calendar function date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) to set the hour and minutes of the current date to the values you got from step 5.

    You should search in the Xcode help system for:

    • Dates and Times (overview)
    • Calendrical calculations (discussion specific to doing math on dates and times)
    • DateFormatter. (See this article for info on the characters to use to build your dateFormat string.)
    • Calendar
    • DateComponents

    Calendar

    Login or Signup to reply.
  2. You can do this by setting up your DateFormatter with the correct timeZone, calendar, defaultDate, and dateFormat. Here’s an example:

    import Foundation
    
    let parser = DateFormatter()
    parser.calendar = Calendar(identifier: .gregorian)
    parser.timeZone = TimeZone(identifier: "US/Eastern")!
    parser.defaultDate = parser.calendar!.date(
        from: DateComponents(
            timeZone: parser.timeZone!, era: 1,
            year: 2021, month: 3, day: 31,
            hour: 12, minute: 0, second: 0))!
    parser.dateFormat = "hh:mm a"
    
    print(parser.date(from: "12:30 PM"))
    

    Output:

    Optional(2021-03-31 16:30:00 +0000)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search