Be Know Do
Be Know Do

Reputation: 83

Date to String [format string] String to Date in Swift

I've racked my brain over this issue all day and can't seem to get a solution. I have a fitness program that queries the Health Data Store. In the predicateForSamples(withStart: myStartDate, end: myEndDate) I am finding that getting a date from a datePicker sends a moment in time and therefore my query does not return the results for the entire day as I'd like. So, I figured if I take that datePicker date and convert it to a starting and ending format my issue would be solved. However, using the let date = dateFormatter.date(from: dateString) is returning the correct date but the time returns as 04:00:00 +0000 for both functions.

If anybody has a suggestion, please feel free to lend a helping hand. Thank you so very much!

func convertStartDate(StartDate: Date) -> Date {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyy-MM-dd '00':'00':'01' +0000"
    let dateString = dateFormatter.string(from: StartDate)
    print("convertingStartDate() - \(dateString)")
    let date = dateFormatter.date(from: dateString)
    print(date as Any)

    return date!
}

func convertEndDate(EndDate: Date) -> Date {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyy-MM-dd '23':'59':'59' +0000"
    let dateString = dateFormatter.string(from: EndDate)
    print("convertingEndDate() - \(dateString)")
    let date = dateFormatter.date(from: dateString)

    return date!
}

Upvotes: 0

Views: 1538

Answers (2)

Mohamed Mostafa
Mohamed Mostafa

Reputation: 1057

This should fix your issue

func convertStartDate(StartDate: Date) -> Date {

    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    dateFormatter.dateFormat = "yyy-MM-dd '00':'00':'01' +0000"
    let dateString = dateFormatter.string(from: StartDate)
    dateFormatter.dateFormat = "yyy-MM-dd HH:mm:ss +0000"
    let date = dateFormatter.date(from: dateString)
    print(date as Any)

    return date!
}

func convertEndDate(EndDate: Date) -> Date {

    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    dateFormatter.dateFormat = "yyy-MM-dd '23':'59':'59' +0000"
    let dateString = dateFormatter.string(from: EndDate)
    dateFormatter.dateFormat = "yyy-MM-dd HH:mm:ss +0000"
    let date = dateFormatter.date(from: dateString)

    return date!
}

Upvotes: 1

Skyler Tanner
Skyler Tanner

Reputation: 136

In addition to above, this is actually fixed by setting dateFormatter.timeZone = TimeZone(secondsFromGMT: 0), as the seconds from GMT is your issue.

Upvotes: 1

Related Questions