Time conversion in swift in different format - swift

I want to convert the time string from 15:00:00 AM to 03:00 PM, this is what I am trying to achieve the results.
var str = "15:00:00 AM" // "15:00:00 AM"
let df = DateFormatter()
df.timeZone = TimeZone.current
df.dateFormat = "HH:mm:ss a" // "Jan 1, 2000, 12:00 AM"
let date = df.date(from: str)
let df1 = DateFormatter()
df1.dateFormat = "hh:mm a"
str = df1.string(from: date!) // "12:00 AM"
Not sure where I am missing tried different approaches but still I am not able to convert the times correctly.
PS: More of the answer, I am checking for the possibility of the conversion, as the time string I am getting is from server end and I can update them for correction.

Good Morning , please try this code
let now = NSDate()
let df = DateFormatter()
df.dateFormat = "hh:mm a"
let result = df.string(from: now as Date)

Related

How can i Convert (2020-02-21 06:07:21 +0000) to "21 Feb 2021 12:00 AM"?

I am using device time to get date components. this works fine for 12 hours formate but if user changes device time to 24 hours it shows wrong calculations. used the following method to convert but it always return nil.
let dateAsString = "\(Date())"
let df = DateFormatter()
df.dateFormat = "yyyy-mm-dd HH:mm:ss zzz"
let date = df.date(from: dateAsString)
df.dateFormat = "d MMM yyyy h:mm a"
let time12 = df.string(from: date!)
print(time12)
So, the core problem you're having is the fact that yyyy-mm-dd is using mm which is minutes and not using MM which is months.
So, if instead, you tried something like...
let dateAsString = "\(Date())"
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"
let date = df.date(from: dateAsString)
df.dateFormat = "d MMM yyyy h:mm a"
let time12 = df.string(from: date!)
it would result in
21 Feb 2020 6:00 PM
Now, the problem is, you could simply do
let df = DateFormatter()
df.dateFormat = "d MMM yyyy h:mm a"
df.string(from: Date())
and get the same result.
Remember, Date does not, in of itself, have a concept of "format", beyond what its "debug" output provides, so you can't change a Date's format, instead, you use a formatter to "represent" the value of the Date in some human readable form.
I have just tried below it works fine on both cases. with AM or PM or 24Format and if you remove a in formatter.dateFormat = "dd MMM yyyy HH:mm a" gives you 24 Format. Even I am using this in my code.
let someDate = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy HH:mm a"
let someDateTime = formatter.string(from: someDate)
print(someDateTime)
Print:
21 Feb 2020 09:35 AM
Try this:
let date : "2021-01-20T21:40:59.416Z"
func setDate(date: String) -> String {
var interval: Double = 0
let convertedDate = date.components(separatedBy: ":")
for (index, part) in convertedDate.reversed().enumerated() {
interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
}
let date = Date(timeIntervalSinceNow: interval)
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "LLLL dd, HH:mm at"
return formatter.string(from: date)}
This will return a date in this format
--> "January 21, 05:30 am"
Try,
let str = "2020-02-21 06:07:21 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd hh:mm:ss zzz"
if let date = formatter.date(from: str) {
formatter.dateFormat = "dd MMM yyyy hh:mm a"
let formattedDate = formatter.string(from: date)
print(formattedDate)
}
Swift-this answer helped me
swift - how to convert date from am/pm to 24 hour format
// posting my work here aswell.
i had device formate in 24H.
i needed in 12H.
so i just converted date object to required formate with this code snippet.
let df = DateFormatter()
df.dateFormat = "d MMM yyyy h:mm a"
let time12 = df.string(from: Date())
print(time12)

Swift Date formating changes to next month when using end of month data?

I live by end of month dates such as "2019-02-28 23:59:59"
print when I print out that date it tells me "Mar-2019". No it is still "Feb-2019"
print(dt1.toString(dateFormat: "MMM-YYYY")
I do use SwiftDate. I also get this issue with the DateFormatter().
so instead of clean code I end up having to subtracting a day to get the correct month-year to display.
Why?
You need to set Timezone & date format properly as below,
let string = "2019-02-28 23:59:59"
let df = DateFormatter()
df.timeZone = .current
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = df.date(from: string)
print(date?.description(with: .current)) //Thursday, February 28, 2019 at 11:59:59 PM Gulf Standard Time
df.dateFormat = "MMM-yyyy"
print(df.string(from: date!)) // Feb-2019

Swift: get the offset value from a date object

as simple as it sounds, but it is hard to find my exact question in google.
I'm trying to ignore the UTC printed out value. I receive multiple dates, this one here is just an example: (it could be +0900, -0200, etc...)
"2017-05-01T12:30:00-0700"
once I apply it to a value using these lines:
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx"
if let result = formatter.date(from: time) {print result}
the value of the dateTimeResult prints:
2017-05-01 19:30:00 UTC
Using swift date objects, how do I slice out the part "-0700", multiply the -7 or +7 (this example is negative) by minutes by seconds. I'll save that total as int in DB (I need it for categorizing the different timezones later). Then applying that total to the incoming date input using this line:
let output = Calendar.current.date(byAdding: .second, value: totalSecs, to: result)
The goal is to end up with this date:
"2017-05-01 12:30:00"
I already have a solution using string manipulation, but I don't think that is the ideal solution. If it must be done by string, how do you do it?
If I understand you correctly you want only the date and time portion ignoring always the time zone information.
In this case strip the time zone from the date string with regular expression
let dateString = "2017-05-01T12:30:00-0700"
let dateStringIgnoringTimeZone = dateString.replacingOccurrences(of: "[+-]\\d{4}", with: "", options: .regularExpression)
print(dateStringIgnoringTimeZone) // "2017-05-01T12:30:00"
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = dateFormatter.date(from: dateStringIgnoringTimeZone)!
I think you should keep the date as it is and then just use DateFormatter to display the time at that timezone
let time = "2017-05-01T12:30:00-0700"
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxxx"
if let result = dateFormatter.date(from: time) {
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print(dateFormatter.string(from: result)) // "2017-05-01 16:30:00 (corresponding time at my location GMT-3)
// to display it at -0700 just set the formatter timaZone
dateFormatter.timeZone = TimeZone(secondsFromGMT: -3600 * 7)
print(dateFormatter.string(from: result)) // "2017-05-01 12:30:00\n"
}
To get the timezone offset from the string:
let hours = Int(time.suffix(5).prefix(3)) ?? 0
let minutes = Int(time.suffix(2)) ?? 0
let offset = hours * 3600 + minutes * 60
print(offset) // -25200

Swift Format Date

This is probably really simple, I have tried lots of different methods but it doesnt seem to work.
I have the following date format in a text field:
Saturday, 2 January 2016 12:00
held as:
var str = "\(dobTextField.text!)"
I would like to convert the string above into the format:
YYYY-mm-dd
any help would be much appreciated!
For Swift 2
Check this :
let str = "Saturday, 2 January 2016 12:00"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, d MMMM yyyy HH:mm"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let outputA = dateFormatter.dateFromString(str)
dateFormatter.dateFormat = "yyyy-MM-dd"
println(dateFormatter.stringFromDate(outputA!))
Output :
2016-01-02

date playground loses a day: SWIFT

I'm trying to play with dates, saving them as strings, then returning them to dates. my output loses a day. Please see below for the playground code:
let date = NSDate()
let formatter = NSDateFormatter()
let secondDateFormatter = NSDateFormatter()
formatter.dateStyle = .FullStyle
let dateString = formatter.stringFromDate(date)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
let finalDate : NSDate = dateFormatter.dateFromString(dateString)!
println(finalDate)
here's the current output:
date = May 7, 2015, 9:16 AM
dateString = "Thursday, May 7, 2015" (perfect)
let finalDate shows: "May 7, 2015, 12:00 AM" (almost perfect except the time)
println(finalDate) reveals : 2015-05-06 16:00:00 +0000
I've searched around and read that it is a time zone modification? I'm not sure. I'll play with it more and see if it works for my needs. Any idea why the output would be different when println is execute vs. just the calculation?