1

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?

Revanth Kausikan
  • 673
  • 1
  • 9
  • 21
MKiOS
  • 73
  • 2
  • 9
  • You see the "+0000" in "03:04:00 +0000"? You live in India? Where there is "5:30" hours difference with UTC, no? So when it's "03:04:00" in UTC, it's in fact "08:34:00" at your place, so that's in fact the same moment, so the same `Date`, no? – Larme Apr 02 '19 at 06:27
  • Yes I live in India. and there is 5:30 hours difference is there with UTC. I got "03:04:00 +0000" because I changed the timeZone calendar.timeZone = .current – MKiOS Apr 02 '19 at 06:29
  • Do I need to convert again to UTC ? – MKiOS Apr 02 '19 at 06:30
  • Set calendar `timeZone` to `UTC` as `calendar.timeZone = TimeZone(abbreviation: "UTC")!` – Kamran Apr 02 '19 at 06:31
  • @Kamran Thanks Changed and got the expected result . Please post in answer So that I can accept it – MKiOS Apr 02 '19 at 06:33
  • Refer this, you might get some help: https://stackoverflow.com/questions/24777496/how-can-i-convert-string-date-to-nsdate/42370648#42370648 – Coder Apr 02 '19 at 06:33

1 Answers1

0

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")!
Kamran
  • 14,987
  • 4
  • 33
  • 51