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
Related
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.
All,
I am trying to convert UTC date to local date . Below is my code. But, even after converting I get both dates in UTC only.
static func getTodayDateInLocalTimeZone() -> Date{
let todaydateInUTC = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let utcDateString = dateFormatter.string(from: todaydateInUTC)
print("Date::: utcDateString: \(utcDateString)")
// Changing to Current timezone
let timzoneIdentiier = TimeZone.current.identifier
let timezone = TimeZone(identifier: timzoneIdentiier)
let abbrv = timezone?.abbreviation()
let dateFormatter1 = DateFormatter()
dateFormatter1.timeZone = TimeZone(identifier: abbrv!)
dateFormatter1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print("Date:::timeZone: \(timzoneIdentiier) == \(String(describing: abbrv))")
let formattedDate1 = dateFormatter1.date(from: utcDateString)
print("Date:::: \(formattedDate1)")
return formattedDate1!
}
Here is what I get when I print
Date::: utcDateString: 2021-01-20T17:39:15+0000
Date:::timeZone: America/New_York == Optional("EST")
Date:::: Optional(2021-01-20 17:39:15 +0000)
Please let me know why is it now changing to the local timezone.
Thanks
First of all, a date does not have a time zone.
So let todaydateInUTC = Date() actually means let todaydate = Date().
The time zone becomes relevant, when you want to present a date to the user.
So instead of creating a new date from a the utcDateString, you just need to create another date string from the same date variable.
let formattedDate1 = dateFormatter1.date(from: utcDateString) becomes let tzDateString = dateFormatter1.string(from: todaydate).
This also means your function should return a string instead of a date.
For example:
func getTodayDateInLocalTimeZone() -> String
{
let now = Date()
// Just for debugging. Not for the result.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let utcDateString = dateFormatter.string(from: now)
print("Date::: utcDateString: \(utcDateString)")
let tz = TimeZone.current
let dateFormatter1 = DateFormatter()
dateFormatter1.timeZone = tz
dateFormatter1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print("Date:::timeZone: \(tz) == \(String(describing: tz.abbreviation()))")
let tzDateString = dateFormatter1.string(from: now)
print("Date:::: \(tzDateString)")
return tzDateString
}
For me it results in:
Date::: utcDateString: 2021-01-20T18:19:44+0000
Date:::timeZone: Europe/Berlin (current) == Optional("CET")
Date:::: 2021-01-20T19:19:44+0100
Hi I am Calculating days from two dates and I am taking same dates to apply leave and that difference should be "1" leave and my code is calculating as "0"
my code:
fromDateTextField.text = 29-06-2019
toDateTextField.text = 29-06-2019
let startDate = fromDateTxtField.text
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let formatedStartDate = dateFormatter.date(from: startDate!)
let currentDate = toDateTxtField.text
dateFormatter.dateFormat = "dd-MM-yyyy"
let formatedEndDate = dateFormatter.date(from: currentDate!)
print(formatedEndDate)
print(formatedStartDate)
let components1 = Set<Calendar.Component>([.day])
let differenceOfDate = Calendar.current.dateComponents(components1, from: formatedStartDate!, to: formatedEndDate!)
print (differenceOfDate.day)
output I am getting is "0"
I am new to iOS and I want to add some milliseconds say (5) to my date. I have used the below code but I am not getting the exact date which I am using
let str_TimeStamp = "2017-08-09 10:26:30.8"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.S"
formatter.timeZone = NSTimeZone(abbreviation: "UTC")! as TimeZone
var dateInput: Date? = formatter.date(from: str_TimeStamp)
dateInput = dateInput?.addingTimeInterval(TimeInterval(5*100))
let endtime = formatter.string(from: dateInput!)
print(endtime)
I am getting the output having some delay of mins
2017-08-09 10:28:10.8
The parameter of the addingTimeInterval is the value to add, in
seconds.
So, addingTimeInterval(TimeInterval(5*100)) - adds 500 seconds = 8 minutes.
If you want to add some milliseconds say (5), you should add this time interval: 0.005
So, the final code is:
let str_TimeStamp = "2017-08-09 10:26:30.8"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
formatter.timeZone = TimeZone(abbreviation: "UTC")
var dateInput = formatter.date(from: str_TimeStamp)
dateInput = dateInput?.addingTimeInterval(5/1000)
if let dateInput = dateInput {
let endtime = formatter.string(from: dateInput)
print(endtime) // prints 2017-08-09 10:26:30.8050
}
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)