Convert time string to Unix time date of the same day - swift

how to convert a string hour to millisecond of the day?
for exemple:
let strDate = "06:00 PM"
Or:
let strDate = "09:00 AM"
my code:
let dateString = "06:00 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
guard let date = dateFormatter.date(from: dateString)
else { fatalError() }
print(date)
for example my string is: 06:00 PM, so I want to have the date in millisecond of today Thursday 20 September 2018 at 06:00 PM

You can set your DateFormatter default date to startOfDay for today, set the formatter locale locale to "en_US_POSIX" when parsing your time then you can simply get your resulting date timeIntervalSince1970 and multiply by 1000:
let strTime = "06:00 PM"
let formatter = DateFormatter()
formatter.defaultDate = Calendar.current.startOfDay(for: Date())
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "hh:mm a"
if let date = formatter.date(from: strTime) {
let milliseconds = date.timeIntervalSince1970 * 1000
print(milliseconds) // 1537477200000
let date2 = Date(timeIntervalSince1970: milliseconds/1000)
print(date2.description(with: .current)) // Thursday, September 20, 2018 at 6:00:00 PM Brasilia Standard Time
}

First, you need to parse the date string:
let dateString = "06:00 PM"
let formatter = DateFormatter()
formatter.defaultDate = Date()
formatter.dateFormat = "hh:mm a"
formatter.locale = Locale(identifier: "en_US_POSIX")
let date = formatter.date(from: dateString)
Then, you need to get the start of day:
let calendar = Calendar.current
let start = calendar.startOfDay(for: date)
After that, get the time interval between date and start:
let timeInterval = date.timeIntervalSince(start)
let milliseconds = timeInterval * 1000.0

Related

Format hour and minute integers as the String "9:30 am"

How can I express hour and minute integer values as a String formatted like "9:30 am"?
Currently, I have:
let hour: Int = 9
let minute: Int = 30
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
let time: String = DateComponentsFormatter.localizedString(from: dateComponents, unitsStyle: DateComponentsFormatter.UnitsStyle.positional)
print(time) // Prints "9:30", not "9:30 am"
I know I can manually concatenate the time meridian at the end, but I'm hoping there's a built in function for this. Perhaps a different UnitsStyle?
You could use DateFormatter to achieve this.
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
formatter.amSymbol = "am"
formatter.pmSymbol = "pm"
let dateString = formatter.string(from: Date())
print(dateString) // prints "12:17 pm"
If you want to only include single digits for the hour, then you only include one "h" in the dateFormat:
formatter.dateFormat = "h:mm a" // prints "1:30 pm" instead of "01:30 pm"
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
formatter.calendar = .current
let hour: Int = 9
let minute: Int = 30
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
If let fixedDate: Date = Calendar.current.date(from: dateComponents) {
let formattedString = formatter.string(from: fixedDate)
print(formattedString) //prints 09:30 AM
}
You need to add current calendar/date to get am or pm from your time from what I know.
EDIT:
Thanks to Leo Dabus in the comments for pointing this out: the above method will result in a date that is on January 1st 0001, if the date is important for you you have to specify the date (day/month/year)
for example:
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
formatter.calendar = .current
let hour: Int = 9
let minute: Int = 30
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.year = Calendar.current.component(.year, from: date)
dateComponents.month = Calendar.current.component(.month, from: date)
dateComponents.day = Calendar.current.component(.day, from: date)
If let fixedDate: Date = Calendar.current.date(from: dateComponents) {
let formattedString = formatter.string(from: fixedDate)
print(formattedString)
}

Date not convert in AM/PM Format in swift

I need to date and time with my own format like time in AM/PM (12 hours).
extension Date {
func getStringFromDateWithUTCFormat() -> ObjTimeStamp {
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.timeZone = TimeZone.init(abbreviation: "UTC")
// Get Date
dateFormatterPrint.dateFormat = "MM/dd/yyyy" //"MMM dd,yyyy"
let date = dateFormatterPrint.string(from: self)
// Get Time
dateFormatterPrint.dateFormat = "hh:mm:ss a"
let time = dateFormatterPrint.string(from: self)
return ObjTimeStamp.init(date: date, time: time, timeStamp: self)
}
}
Update
Calling function
self.currentDate = Date()
let objTimeStamp = currentDate.getStringFromDateWithUTCFormat()
Perfect work when device time in 12-hour format when I try to change device time in 24-hour formate then given wrong time format.
set your dateFormatter locale to en-US then try to convert, it's works for me when iPhone's time format is 24 hour:
let date = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en-US")
formatter.dateFormat = "hh:mm a"
let time12 = formatter.string(from: date)
print(time12)
output:
01:37 PM

Convert From String To date with 12 hours time formatting

Since yesterday I'm trying to solve this issue but I give up. Now I have string date "2018-10-30 01:00 PM" and when I'm trying to convert it to date the time format will change to 24 hours. I mean it will be like "2018-10-30 13:00:00 UTC".
Here is my code:
let dateFormatter5 = DateFormatter()
dateFormatter5.dateFormat = "yyyy-MM-dd hh:mm a"
dateFormatter5.locale = Locale(identifier: "en_US_POSIX")
dateFormatter5.timeZone = NSTimeZone(abbreviation: "GMT+0:00")! as TimeZone
let now = dateFormatter5.date(from: "2018-10-30 01:00 pm")!
I need to convert this string with the same time format (12 hours).
Any idea?
If your original date string is UTC timezone:
let dateStr = "2018-10-30 01:00 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
if let now = dateFormatter.date(from: dateStr) {
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'UTC'"
dateFormatter.string(from: now) // "2018-10-30 13:00:00 UTC"
}

Get NSDate and convert it from the 24 hour format to 12 hour format in swift

I've seen this post for other languages but not for swift. I have a date saved in the format of 2015-08-31 21:36:00 +0000 and I'm able to extract the day, month, year and weekday with the code below to produce Monday, August 31, 2015. When I try to use:
let hourInt = components.hour
var hourString = String(hourInt)
It prints a four hour difference. In this case "17" for the "21". How do I
display it as 9:36 P.M.?
let flags: NSCalendarUnit = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear
let date = NSDate()
let dateFormatter: NSDateFormatter = NSDateFormatter()
let components = NSCalendar.currentCalendar().components(flags, fromDate: array.date)
let weekday = components.weekday
let weekdays = dateFormatter.weekdaySymbols
let weekdayString = weekdays[weekday-1] as! String
let month = components.month
let months = dateFormatter.monthSymbols
let monthString = months[month-1] as! String
let dayInt = components.day
var dayString = String(dayInt)
let year = components.year
let yearString = String(year)
println(weekdayString + ", " + monthString + " " + dayString + ", " + yearString)
Your date string suffix +0000 means it is UTC time if you want to display time at UTC you need to specify it when setting your date formatter.
let dateString = "2015-08-31 21:36:00 +0000"
let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = df.dateFromString(dateString) {
// now you have your date object
// to display UTC time you have to specify timeZOne UTC
df.timeZone = NSTimeZone(forSecondsFromGMT: 0)
df.dateFormat = "EEEE, MMMM dd, yyyy h:mm:ss a"
let stringFromDate = df.stringFromDate(date)
println(stringFromDate) // "Monday, August 31, 2015 9:36:00 PM"
}
If you want to strip the time zone information, pass the GMT time zone.
This code does quite the same as yours
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
println(dateFormatter.stringFromDate(array.date))
Setting locale of NSDateFormatter to en_US_POSIX fixed issue for me.
let sharedFormatter:NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier:"en_US_POSIX")
return formatter
}()
sharedFormatter.dateFormat = "MMM d YYYY, h:mm a"
let dateString = sharedFormatter.stringFromDate(NSDate())
// Aug 2 2016, 5:45 PM
Swift 5.0
let dateString = "2015-08-31 21:36:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = dateFormatter.date(from: dateString) {
// now you have your date object
// to display UTC time you have to specify timeZOne UTC
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy h:mm:ss a"
let stringFromDate = dateFormatter.string(from: date)
print(stringFromDate) // "Monday, August 31, 2015 9:36:00 PM"
}

Xcode Swift am/pm time to 24 hour format

I am trying to convert an am/pm format time to a 24 hour format time
6:35 PM to 18:35
I tried this piece of code on playground but it doesn't seem to
work if I put the time alone
let dateAsString = "02/12/15, 6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH"
let date = dateFormatter.dateFromString(dateAsString) //returns nil
Does anyone know how to accomplish this?
Just convert it to a date using NSDateFormatter and the "h:mm a" format and convert it back to a string using the "HH:mm" format. Check out this date formatting guide to familiarize yourself with this material.
let dateAsString = "6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // fixes nil if device time in 24 hour format
let date = dateFormatter.dateFromString(dateAsString)
dateFormatter.dateFormat = "HH:mm"
let date24 = dateFormatter.stringFromDate(date!)
Swift 3
Time format 24 hours to 12 hours
let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print("12 hour formatted Date:",Date12)
output will be 12 hour formatted Date: 1:15 PM
Time format 12 hours to 24 hours
let dateAsString = "1:15 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm"
let Date24 = dateFormatter.string(from: date!)
print("24 hour formatted Date:",Date24)
output will be 24 hour formatted Date: 13:15
Swift 3 *
Code to convert 12 hours (i.e. AM and PM) to 24 hours format which includes-
Hours:Minutes:Seconds:AM/PM to Hours:Minutes:Seconds
func timeConversion24(time12: String) -> String {
let dateAsString = time12
let df = DateFormatter()
df.dateFormat = "hh:mm:ssa"
let date = df.date(from: dateAsString)
df.dateFormat = "HH:mm:ss"
let time24 = df.string(from: date!)
print(time24)
return time24
}
Input
07:05:45PM
Output
19:05:45
Similarly
Code to convert 24 hours to 12 hours (i.e. AM and PM) format which includes-
Hours:Minutes:Seconds to Hours:Minutes:Seconds:AM/PM
func timeConversion12(time24: String) -> String {
let dateAsString = time24
let df = DateFormatter()
df.dateFormat = "HH:mm:ss"
let date = df.date(from: dateAsString)
df.dateFormat = "hh:mm:ssa"
let time12 = df.string(from: date!)
print(time12)
return time12
}
Input
19:05:45
Output
07:05:45PM
Below is the swift 3 version of the solution -
let dateAsString = "6:35:58 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm:ss a"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm:ss"
let date24 = dateFormatter.string(from: date!)
print(date24)
Here is the answer with more extra format.
** Xcode 12, Swift 5.3 **
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var dateFromStr = dateFormatter.date(from: "12:16:45")!
dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16
dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM
dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000
dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000
dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000
dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM
dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000
dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00
//Output: Customisable AP/PM symbols
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"
//Output: Pm
// Usage
var timeFromDate = dateFormatter.string(from: dateFromStr)
print(timeFromDate)
Swift version 3.0.2 , Xcode Version 8.2.1 (8C1002) (12 hr format ):
func getTodayString() -> String{
let formatter = DateFormatter()
formatter.dateFormat = "h:mm:ss a "
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let currentDateStr = formatter.string(from: Date())
print(currentDateStr)
return currentDateStr
}
OUTPUT : 12:41:42 AM
Feel free to comment. Thanks
Use this function for date conversion, its working fine when your device in 24/12 hr format
See https://developer.apple.com/library/archive/qa/qa1480/_index.html
func convertDateFormatter(fromFormat:String,toFormat:String,_ dateString: String) -> String{
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = fromFormat
let date = formatter.date(from: dateString)
formatter.dateFormat = toFormat
return date != nil ? formatter.string(from: date!) : ""
}
Unfortunately apple priority the device date format, so in some cases against what you put, swift change your format to 12hrs
To fix this is necessary to use setLocalizedDateFormatFromTemplate instead of dateFormat an hide the AM and PM
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("HH:mm:ss a")
formatter.amSymbol = ""
formatter.pmSymbol = ""
formatter.timeZone = TimeZone(secondsFromGMT: 0)
var prettyDate = formatter.string(from: Date())
You can check a very useful post with more information detailed in
https://prograils.com/posts/the-curious-case-of-the-24-hour-time-format-in-swift
Here is code for other way around
For Swift 3
func amAppend(str:String) -> String{
var temp = str
var strArr = str.characters.split{$0 == ":"}.map(String.init)
var hour = Int(strArr[0])!
var min = Int(strArr[1])!
if(hour > 12){
temp = temp + "PM"
}
else{
temp = temp + "AM"
}
return temp
}
let calendar = Calendar.current
let hours = calendar.component(.hour, from: Date())
let minutes = calendar.component(.minute, from: Date())
let seconds = calendar.component(.second, from: Date())
I am using a function here in my case by which I am updating a label with the normal time format and after that I am storing the selected time's 24hr format to do some another tasks..
Here is my code...
func timeUpdate(sender: NSDate)
{
let timeSave = NSDateFormatter() //Creating first object to update time label as 12hr format with AM/PM
timeSave.timeStyle = NSDateFormatterStyle.ShortStyle //Setting the style for the time selection.
self.TimeShowOutlet.text = timeSave.stringFromDate(sender) // Getting the string from the selected time and updating the label as 1:40 PM
let timeCheck = NSDateFormatter() //Creating another object to store time in 24hr format.
timeCheck.dateFormat = "HH:mm:ss" //Setting the format for the time save.
let time = timeCheck.stringFromDate(sender) //Getting the time string as 13:40:00
self.timeSelectedForCheckAvailability = time //At last saving the 24hr format time for further task.
}
After writing this function you can call this where you are choosing the time from date/time picker.
Thanks,
Hope this helped.
this is similar to our friends answer: https://stackoverflow.com/a/43801717/2796837 but using all our internet friends ideas I came up with the following more complete singular solution:
let amPmFormat = "h:mm a"
let twentyFourHFormat = "HH:mm"
func hourMinuteParser(date: Date) -> KotlinInt{
let formatter = DateFormatter()
if DateFormatter.dateFormat(fromTemplate: "j",options:0, locale: Locale.current)!.contains("a") {
formatter.dateFormat = amPmFormat
}else{
formatter.dateFormat = twentyFourHFormat
}
let stringTime = formatter.string(from: date)
let time = formatter.date(from: stringTime)
formatter.dateFormat = twentyFourHFormat
let time24 = formatter.string(from: time!)
let timeWithoutSpecialCharacters = time24.replacingOccurrences(of: ":", with: "")
let int2 = Int32(timeWithoutSpecialCharacters) ?? 0
return KotlinInt(int: int2)
}
This will parse your time even independent of the format it comes and outputs it into HH:mm, you could change the third format change into whatever you would want.