How to get current time hour in system time format - ios

I need to get the current hour and minute as per the system time format, e.g for system time 7:05 PM, sysHour should be 7. For 19:05, sysHour should be 19
Currently, I am using the code below but it gives sysHour = 19 instead of 7.
let date = Date()
let calendar = Calendar.current
let sysHour = calendar.component(.hour, from: date)
let sysMinutes = calendar.component(.minute, from: date)
Please help
Thanks

Use a DateFormatter using .short or maybe .medium for the timeStyle.
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.dateStyle = .none
let time = formatter.string(from: Date())
The result will depend on the user's locale and their time settings.

Related

why i get an error in the date formatter code?

I’m trying to convert my AM PM time pickers to 24h format to print the start and end time to calculate the price but i got an unknown error. attached is photo of my UI to simplify the idea and my code.
Note: the end time is automatically shows after i choose the start time
#objc func donePressed(){
// formatter
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
startTimeTxt.text = formatter.string(from: StartTimePicker.date)
self.view.endEditing(true)
endTimeTxt.text = formatter.string(from: EndTimePicker.date)
self.view.endEditing(true)
let starttimecal = StartTimeTxt.text!
let endtimecal = EndTimeTxt.text!
let StartTo24 = starttimecal
let EndTo24 = endtimecal
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let sTime = dateFormatter.date(from: startTo24)
dateFormatter.dateFormat = "HH:mm"
let sTime24 = dateFormatter.string(from: sTime!)
print("24 hour formatted Date:", sTime24)
let eTime = dateFormatter.date(from: endTo24)
dateFormatter.dateFormat = "HH:mm"
let eTime24 = dateFormatter.string(from: eTime!) // here the fatal error comes after i choose the start time from simulator
print("24 hour formatted Date:", eTime24)
}
To get the 12h time format to display in the text fields you can use the formatter you already have but I also like to set the locale
let dateFormatter12h = DateFormatter()
dateFormatter12h.locale = Locale(identifier: "en_US_POSIX")
dateFormatter12h.dateFormat = "h:mm a"
To calculate the time difference there is a function for that in the Calendar class, here we calculate the number of hours and minutes between two dates (this is an assumption since I don't know exactly what calculation you want to do)
let hourAndMinutes = Calendar.current.dateComponents([.hour, .minute], from: startDate, to: endDate)
Below is a more complete example
//Sample data
let startDate = Date()
let endDate = startDate.addingTimeInterval(3.25*60*60) //add 3h and 15 minutes
// Format and print in 12h format
let dateFormatter12h = DateFormatter()
dateFormatter12h.locale = Locale(identifier: "en_US_POSIX")
dateFormatter12h.dateFormat = "h:mm a"
let start = dateFormatter12h.string(from: startDate)
let end = dateFormatter12h.string(from: endDate)
print(start, end)
// Calculate time difference in hours and minutes
let hourAndMinutes = Calendar.current.dateComponents([.hour, .minute], from: startDate, to: endDate)
print(hourAndMinutes)
// Calculate price, the formula is just an example
let price = hourAndMinutes.hour! * 15 + hourAndMinutes.minute! * 15 / 60
print(price)
Output
6:46 PM 10:01 PM
hour: 3 minute: 15 isLeapMonth: false
48

Separate Time from Date String ios

How to separate hour and minute from date .
let StDate = "2021-04-03T10:15:00Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm"
if let date1 = formatter.date(from: StDate) {
let tme = dateFormatterPrint.string(from: date1)
print(tme)
}
Out Put
15:45
How to get 10:15
This most likely happens because you reside in a GMT+5 time zone. Meanwhile, your date string is UTC.
Use this to override the time zone:
dateFormatterPrint.timeZone = TimeZone(abbreviation: "UTC")
Your dateFormattedPrint by default uses your local timezone. Add
dateFormatterPrint.timeZone = TimeZone(identifier: "GMT")
to make it use GMT.

Using Date() in a 12-Hour Time Device

Was trying to use the current date with Date() and making some operation on it.
print("Date() -> ", Date())
When the device is on a 24-Hour Time mode:
Date() -> 2018-07-10 09:06:38 +0000
When the device is on a 12-Hour Time mode:
Date() -> 2018-07-10 99:04:09 AM +0000
Is this normal to have 99:04:09 for the 12-Hour Time mode? If yes, how do you manage your operations depending on the Hour Time mode?
Try to convert Date() into string with the below code and check what you are getting in 12hour date formate.
You can convert Date() into a device's date formate as per below code.
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateStyle = .short
formatter.timeStyle = .short
let dateString = formatter.string(from: Date())// it will print date in device's current date formate style.
For more reference on dateStyle/timeStyle refer this answer - https://stackoverflow.com/a/46668669/3705770
use this code
let formatter = DateFormatter()
// initially set the format based on your datepicker date
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: myDate)
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)

Date formatting with .long or .full not resulting in hours/minutes/days/seconds

I want to get the current date as a string showing granularity down to hours/minutes/seconds, however the following code will only show "Friday Jan 20th, 2017". I've tried with a dateStyle of none, .medium, .long, .full. They only display a granularity down to the nearest day, how can I get finer granularity than that?
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
let now = Date()
let dateString = dateFormatter.string(from: now)
You have to set a timeStyle as well. Example (German locale):
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .medium
let now = Date()
let dateString = dateFormatter.string(from: now)
print(dateString) // Freitag, 20. Januar 2017 um 18:39:04
Alternatively, set a dateFormat. Example:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "EEEE ddMMMyyyy HHmmss",
options: 0, locale: Locale.current)
let now = Date()
let dateString = dateFormatter.string(from: now)
print(dateString) // Freitag, 20. Jan. 2017, 18:46:36
You're very close! you also need to give the DateFormatter a timeStyle.
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.timeStlye = .full // options of short, medium, long, and full
let now = Date()
let dateString = dateFormatter.string(from: now)
.full from the above prints Friday, January 20, 2017 at 12:40:23 PM Eastern Standard Time
In order to see different time style you will need to set a value for the timeStyle on the dateFormatter. e.g
dateFormatter.timeStyle = .full
The following formats work for timeStyle as well as dateStyle
case none
case short
case medium
case long
case full
See Apple's docs if you want to learn more about date formatters.
https://developer.apple.com/reference/foundation/dateformatter

How can I convert the 24 hour time format to 12 hour time format?

I can get the 24 hour style time, but how do I get the 12 hour format with the am and pm?
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute, .Second], fromDate: date)
let hour = components.hour
let minutes = components.minute
As you say, you should use NSDateFormatter for your desired format. Hope this will help you.
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "hh:mm a"
let time = formatter.stringFromDate(date)
For more information about date formatter see NSDateFormatter
Swift 3.1 Answer
let date = Date() //Jun 1, 2017, 10:22 AM"
let formatter = DateFormatter() //<NSDateFormatter: 0x608000244380>
formatter.dateFormat = "hh:mm a" //<NSDateFormatter: 0x608000244380>
let time = formatter.string(from: date) //"10:22 AM"
Time format must be in 'hh' not HH
formatter.dateFormat = "hh:mm a"
let str=dict["startDateTime"] as! String //if the date is in the array
let str="16:00" //if you want to use static date
let index=str.index(str.startIndex, offsetBy: 11)
let end_index=str.index(str.endIndex, offsetBy:-3)
let dateAsString = str[index ..< end_index]
let dateFormatter=DateFormatter()
dateFormatter.dateFormat="HH:mm"
let date = dateFormatter.date(from: String(dateAsString))
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print(Date12)

Resources