Is DateFormatter class broken in swift 3? - swift

I am trying to use Date class which is provided from Swift 3 library. I am not sure if I am doing it right.
When I print Date it prints correct date, but when I try to convert it from date to string it changes the date to something else.
let today = Date()
print(" Date object : \(today)")
let format = DateFormatter()
format.dateFormat = "mm/dd/yy"
print(" Date to String : \(format.string(from: today)")
Which gives the output:
Date object : 2017-06-03 18:13:39 +0000
Date to String : 13/03/17

mm is the format specifier for minutes, hence why the output returns 13 instead of 06, which is the time in minutes at which you called Date().
You'll need to use MM to display the month.
See the unicode report on date specifiers for more information: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

No it doesnt.
Your format is Minute, Day and Year.
Works exactly as it should.
Try MM istead of mm.

Related

Why does print(date object) show a different date than what the value actually is? [duplicate]

This question already has answers here:
NSDate() or Date() shows the wrong time
(2 answers)
Closed 2 years ago.
I am playing around with DateFormatter in xcode playground to try to learn the basic of how the date object works in swift.
The following code gave my strange results when i tried to print the result from a string to date conversion from this string "050478" (5. April 1978) to a date . In Norway our social security number starts with ddMMyy, so it is that number i want to convert to a date.
import UIKit
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "dd/MM/yy"
let myDateString = "05/04/78"
if let myDate = dateFormatterGet.date(from: myDateString)
{
print(myDate)
}
As you can see, the print(myDate) command gives me the wrong date from the day before what i a gave as argument to the dateformatter (1978-04-04)
The local time zone in Norway on May 5th at 0:00 is UTC+0100.
However print() displays dates always in UTC(+0000) which is May 4th at 23:00.
Replace
print(myDate)
with
print(myDate.description(with: .current))
to get the local date and time

DateFormatter giving me incorrect result while I am converting String into Date in UK region and Timezone is Muscat

I want "yyyy-MM-dd HH:mm:ss", with time in 24 hour format, but as i m having 12 hrs date format setting in my phone and Timezone is set to the Muscat ,the date which I am getting is always 12 hrs format, while i m checking with UK region. I am able to change Date() into string in 24 hrs format but while I am changing 24 hrs string into 24 hrs Date , It always give me 12 hrs Date format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let dateToString = dateFormatter.string(from: Date()) //2020-04-06 15:47:16
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let dateFromString = dateFormatter.date(from: dateToString)
print(dateFromString) // 2020-04-06 1:47:25 pm +0000
A Date object just represents a point in time. The “should I show it in 12 hour clock or 24 hour clock” is not something that Date objects know about. This is a feature of strings generated by (or consumed by) a DateFormatter.
So, a few thoughts:
A date formatter’s dateFormat (and its locale) dictates what a string will look like when you call string(from:). (It will also dictate how to interpret a string and create a Date object when you call date(from:), but that’s not relevant here.)
So, if you’re looking for a string representation of a date using a 24 hour clock, look at the string generated by the date formatter’s string(from:) method. This is the dateToString string in your example.
But, if you subsequently generate a Date object from the formatter’s date(from:) method, that resulting Date will not capture whether to use 12 vs 24 hour clock. If you print this Date object, it won’t reflect your 12/24 hour clock preference.
Bottom line, only concern yourself with am/pm vs 24-hour clock when looking at String objects generated by (or passed to) the DateFormatter. Don’t worry about the format of the output when you print a Date object, as that’s for debugging purposes only and won’t capture this am/pm vs 24-hour clock dimension.
You said:
Final statement is giving me “2020-04-09 4:23:27 am +0000” format.
If you’re seeing the +0000, that suggests that you are printing the Date object, itself. The dateFormat and locale of a DateFormatter only controls the format of the string generated by string(from:) (and how strings are parsed).
So, print the string generated by DateFormatter, not Date objects. The print of a Date object will always be in this predefined format. Within the app, if you need the output in a given format, use the String generated by DateFormatter, not Date objects.
Consider a more obvious example of the issue where the DateFormatter is used to create a string in a very different format:
let now = Date()
print(now) // 2020-04-07 11:54:58 +0000
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .long
let string = formatter.string(from: Date())
print(string) // April 7, 2020 at 4:54:58 AM PDT
if let date = formatter.date(from: string) {
print(date) // 2020-04-07 11:54:58 +0000
}
So, even though that formatter successfully converted a Date to a String, and back, that final print statement uses the same fixed format that the first print statement did, because I’m just printing a Date object. I’m not concerned that the that last print statement didn’t honor the configuration of my DateFormatter. I wouldn’t expect it to. When I print a Date, it’s always in that fixed, predefined format. I only worry about the format of the strings generated by the DateFormatter (the second print statement).
As an aside, there are secondary questions about your "yyyy-MM-dd HH:mm:ss" format. What timezone does this represent? Your local timezone? Your server’s timezone? GMT/UTC/Zulu? We often use ISO8601/RFC3339 date strings (like 2020-04-07T11:54:58Z) to remove this ambiguity. You should get your arms around your original question first, but when you have that behind you, you’ll want to take a hard look at why you’re storing it in this format, and how you want to deal with timezones correctly. But first things first.

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 :-).

How to Convert UNIX epoch time to Date and time in ios swift

I'm trying to convert the UNIX epoc time to datetime format using the below code
var epocTime = NSTimeInterval(1429162809359)
let myDate = NSDate(timeIntervalSince1970: epocTime)
println("Converted Time \(myDate)")
the actual result is (Thu, 16 Apr 2015 05:40:09 GMT) but am getting something like (47258-05-14 05:15:59 +0000) Can anyone please tel me how to achieve this.
update: Xcode 8.2.1 • Swift 3.0.2 or later
You need to convert it from milliseconds dividing it by 1000:
let epochTime = TimeInterval(1429162809359) / 1000
let date = Date(timeIntervalSince1970: epochTime) // "Apr 16, 2015, 2:40 AM"
print("Converted Time \(date)") // "Converted Time 2015-04-16 05:40:09 +0000\n"
Swift 5
I am dealing with a date in a JSON api which is defined as an Int and an example of the timestamp is 1587288545760 (UTC)
The only way I could display that value as a Date in a way that made any sense was to truncate the last 3 digits and convert THAT resultant date to "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
This was the function I created to achieve that.
func convertDate(dateValue: Int) -> String {
let truncatedTime = Int(dateValue / 1000)
let date = Date(timeIntervalSince1970: TimeInterval(truncatedTime))
let formatter = DateFormatter()
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return formatter.string(from: date)
}
It works for me and I end up with a date that looks like this:
"2020-04-19T09:29:05.000Z"
..and it reflects the fact that the original time stamp is exactly that date.
Hope that helps anyone having the same issue.
It seems that your time information is "milliseconds since 1970". Should have been straightforward to figure out: We are about 46 years after 1970, but your date is about 45,000 after 1970.
NSTimeInterval is based on SECONDS.
Convert your number to double and divide by 1000.0.