Search code examples
iosswiftnsdateformatter

Converting the string to date giving different format


Converting from string to date and date to string time format is changing the original data.

Tried with dateComponents as well by giving the hour and minute

var calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: calFrom)
calendar.timeZone = .current

// Specify date components
var dateComponents:DateComponents = calendar.dateComponents([.year, .month, .day, .hour], from: Date())
dateComponents.year = components.year
dateComponents.month = components.month
dateComponents.day = components.day
dateComponents.hour = 08//Cutomised hour
dateComponents.minute = 34//Cutomised Minutes

// Create date from components
let someDateTime = calendar.date(from: dateComponents)
print(someDateTime!)

Actual Output:

2019-04-02 03:04:00 +0000

Expected Output:

2019-04-02 08:34:00 +0000

I tried with below code as well. Converting the date to String and manually appending the hour and minutes to the string and converting back to the date.

let calFrom = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
var calFromDate = formatter.string(from: calFrom)

calFromDate = calFromDate + " 09" + ":30"
print(calFromDate)
//Output 02/04/2019 09:30
formatter.dateFormat = "dd/MM/yyyy hh:mm"
formatter.locale = Locale.current// set locale to reliable       US_POSIX

let date1 = formatter.date(from: calFromDate)
print(date1!)

Actual Output:

2019-04-02 04:00:00 +0000

Expected Output:

02/04/2019 09:30

How to get the exact time that has given in the output?


Solution

  • Date used to update the hour and minute components has UTC timezone so calendar should also have the same timeZone as below,

    calendar.timeZone = TimeZone(abbreviation: "UTC")!