Swift 5 - Dateformatter not working as expected [duplicate] - swift

This question already has answers here:
Swift - Get local date and time
(11 answers)
Closed 1 year ago.
I was playing around with date formatter in swift, but the AM/PM thing is not working in my code.
import Foundation
let dtstr = "Tuesday, July 28, 2020 4:15:45 PM"
let formatter = DateFormatter()
formatter.dateFormat = "eeee, MMMM d, yyyy h:m:s a"
let date = formatter.date(from: dtstr)
print(date)
the output is this: Optional(2020-07-28 08:15:45 +0000). However, it should be 16:15:45 instead of this. Any idea why?
Thanks!

Date has no information about time zone, and default string representation is using a greenwich one. You can see it +0000 part in your string.
You can get description for your own time zone like this:
date.description(with: .current)

Related

Getting start of month and end of month with time for December [duplicate]

This question already has answers here:
NSDateFormatter show wrong year
(1 answer)
first and last day of the current month in swift
(11 answers)
Getting back a date from a string
(3 answers)
Closed 2 years ago.
As the title indicates I'm trying to get the start and end of month with a time component for December. I'm sure I'm missing something obvious related to TimeZones but I can't seem to get a same year for both dates in in PST time zone.
Here's how I get the start of month and day:
NOTE: If you try this in the swift REPL there's a bug that shows nil result even though the
variables have a non-nil value, use print or debugPrint to show the value.
let cal = Calendar.current
let startOfMonth = cal.startOfDay(for: cal.date(from: DateComponents(year: 2020, month: 12, day: 1))!)
Here's how I calculate the end of day up to seconds:
let startOfNextMonth = cal.date(byAdding: DateComponents(month: 1), to: startOfMonth)!
let endOfMonth = cal.date(byAdding: DateComponents(second: -1), to: startOfNextMonth)!
By this point startOfMonth has the value: Optional(2020-12-01 08:00:00 +0000) and endOfMonth has a value of Optional(2021-01-01 07:59:59 +0000)
Which seems fine and dandy because times are printed in GMT (UTC) and if I subtract 8 hours endOfMonth it would end up like Optional(2020-12-31 23:59:59 +0000)
However the trouble comes when formatting the endOfMonth date, even If I set the TimeZone to "America/Los_Angeles" I still get the year value as 2021 and not as 2020, here's how I create my formatter:
let fmt = DateFormatter()
fmt.timeZone = .current // "America/Los_Angeles"
fmt.dateFormat = "d/Y"
fmt.string(from: endOfMonth!) // $R13: String = "31/2021"
What's going on?, wouldn't conversion to the default Time zone yield the year 2020?
After setting the formatter dateStyle property to .long and obtaining the correct year printed (though not the format I wanted) I realized that the issue might be in the dateFormat.
After reading a bit more of the documentation, I found a link to the format specifiers
Date Format Swift Docs
Date Formatting Guide
Unicode Date Format Patterns
Eventually I found out that the Y specifier is essentially a "Week of Year" vs the y specifier which is "Year of Era".
Using the following fixed my issue:
let formatter = DateFormatter()
formatter.dateFormat = "d/y"
formatter.string(from: endOfMonth!) // $R1: String = "31/2020"

How to get the Seconds from Date - Swift 4 [duplicate]

This question already has answers here:
Find difference in seconds between NSDates as integer using Swift
(7 answers)
Closed 4 years ago.
I am trying to get the number of SECONDS between two Dates.
for an example having a date like this:
let savedDate = Jun 25, 2018 at 12:48:09 AM -> (just printed as example date)
let currentDate = Date()
Can anyone help me understand how to find the number of second passed as a Double preferably?
Date#timeIntervalSince(_:) is probably what you're looking for.
Playground Example...
I modified the format so it would parse, but the basic concept works.
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd, yyyy hh:mm:ss a"
let date = formatter.date(from: "Jun 25, 2018 12:48:09 AM")
if let date = date {
Date().timeIntervalSince(date)
}
Will output
29793.5867500305

DateFormatter displaying Date Wrongly in iPhone device [duplicate]

This question already has answers here:
Getting date from [NSDate date] off by a few hours
(3 answers)
Closed 5 years ago.
I did an extension for Date that returns a formatted string:
extension Date {
var myFormattedDate : String {
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "EEEE, MMMM d, y (HH:mm a)"
return formatter.string(for: self)!
}
}
On runtime, I set a breakpoint inside the myFormattedDate property.
po self printed:
2017-09-05 08:50:00 +0000
po formatter.string(for: self)! printed:
Tuesday, September 5, 2017 (11:50 AM)"
What could be the problem?
Thanks!
Printing a Date always returns an UTC time, regardless of the local time zone. Just avoid printing a Date object directly if you want to see the date with the proper time zone in your console.

Big int to date time format in swift [duplicate]

This question already has answers here:
How to Convert UNIX epoch time to Date and time in ios swift
(3 answers)
Closed 2 years ago.
I am doing this in swift:
let date = NSDate(timeIntervalSince1970: 1432233446145.0)
println("date is \(date)")
The log gives me this:
date is 47355-09-02 23:55:45 +0000
Then I try to get an interval back out just for testing:
let tI = expirationDate.timeIntervalSinceDate(date)
println("tI = \(tI)")
I get:
tI = 0.0
What am I doing wrong?
I can seem to make the timeIntervalSince1970 call work properly. Is there any known issued with that in Swift, or am I missing something here?
1432233446145 most probably is a time interval given in milliseconds:
let date = NSDate(timeIntervalSince1970: 1432233446145.0/1000.0)
print("date is \(date)")
// date is 2015-05-21 18:37:26 +0000
Swift 3 and later:
let date = Date(timeIntervalSince1970: 1432233446145.0/1000.0)
I think your timestamp is incorrect. This results in your date being september 2nd, 47355.
If I use the following I get the date for (right about) now:
let date = NSDate(timeIntervalSince1970: 1431024488)
println("date is \(date)")
// "date is 2015-05-07 18:48:08 +0000"
The printed date is not a localized timestamp, so you'll have to do some localization of your own I suppose. An example:
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
println("formatted date is \(formatter.stringFromDate(date))")
// "formatted date is 07-05-2015 20:48:08"
And for completeness I also checked with an expiration date that's 1100 seconds larger than the initial date:
let expirationDate = NSDate(timeIntervalSince1970: 1431025588)
let diff = expirationDate.timeIntervalSinceDate(date)
println("expires in: \(diff)")
// "expires in: 1100.0"
So, the timeIntervalSince1970 seems to work fine, I think your interval was just not what you wanted it to be.
From your code and the log content follows:
date.isEqual(expirationDate)
--> Your stuff has just expired :-).

NSDate timeIntervalSince1970 not working in Swift? [duplicate]

This question already has answers here:
How to Convert UNIX epoch time to Date and time in ios swift
(3 answers)
Closed 2 years ago.
I am doing this in swift:
let date = NSDate(timeIntervalSince1970: 1432233446145.0)
println("date is \(date)")
The log gives me this:
date is 47355-09-02 23:55:45 +0000
Then I try to get an interval back out just for testing:
let tI = expirationDate.timeIntervalSinceDate(date)
println("tI = \(tI)")
I get:
tI = 0.0
What am I doing wrong?
I can seem to make the timeIntervalSince1970 call work properly. Is there any known issued with that in Swift, or am I missing something here?
1432233446145 most probably is a time interval given in milliseconds:
let date = NSDate(timeIntervalSince1970: 1432233446145.0/1000.0)
print("date is \(date)")
// date is 2015-05-21 18:37:26 +0000
Swift 3 and later:
let date = Date(timeIntervalSince1970: 1432233446145.0/1000.0)
I think your timestamp is incorrect. This results in your date being september 2nd, 47355.
If I use the following I get the date for (right about) now:
let date = NSDate(timeIntervalSince1970: 1431024488)
println("date is \(date)")
// "date is 2015-05-07 18:48:08 +0000"
The printed date is not a localized timestamp, so you'll have to do some localization of your own I suppose. An example:
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
println("formatted date is \(formatter.stringFromDate(date))")
// "formatted date is 07-05-2015 20:48:08"
And for completeness I also checked with an expiration date that's 1100 seconds larger than the initial date:
let expirationDate = NSDate(timeIntervalSince1970: 1431025588)
let diff = expirationDate.timeIntervalSinceDate(date)
println("expires in: \(diff)")
// "expires in: 1100.0"
So, the timeIntervalSince1970 seems to work fine, I think your interval was just not what you wanted it to be.
From your code and the log content follows:
date.isEqual(expirationDate)
--> Your stuff has just expired :-).