Getting hours from NSDate via components - swift

I am not sure what I am missing here. I have Date object in swift, printed the description out and it is: "2000-01-01 07:00:00 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "h:mm"
let durationDate = DateHelper.durationFormatter.date(from: “07:00”)!
let hours = Calendar.current.component(.hour, from: durationDate)
For some odd reason the hours is coming out as 0. Not sure what I am missing here?

Looks like I didn't take in account timezone. I am in +7 hours to UTC so it worked out perfectly to be zero.

Related

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

wrong time using NSDateFormatter

I know there is several question about this. But i tried all the recommendation and still the time doesn't match the time atonmy real device.
let dater = NSDate()
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.locale = NSLocale.currentLocale()
dayTimePeriodFormatter.timeZone = NSTimeZone(name: "UTC")
dayTimePeriodFormatter.dateFormat = "H:s"
var dateString = dayTimePeriodFormatter.stringFromDate(dater)
Device(real) time : 22:11 . dateString output : 00:36
Any suggestions? Thanks!
As Nick points out, you're using UTC as your time zone, and you can get to the local time zone with NSTimeZone.systemTimeZone()
It's also likely that you don't really intend to use just the hours (H) and seconds (s) You probably also want the minutes (m). Try using a dateFormat of "H:m:s"
Better yet, use "H:mm:ss" which will force the minutes and seconds to be two digits, as opposed to just one, so you don't wind up with "10:4:3"
Have you tried dayTimePeriodFormatter.dateFormat = "HH:mm"?
Apple uses fixed Internet. Check out here to see some examples. This may be helpful

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

NSDateFormatter return wrong date + Swift

Code :
let dateString = "2016-04-02"
var formatter: NSDateFormatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(abbreviation: "GMT +3:00")
formatter.dateFormat = "yyyy-MM-dd"
println("dateString: \(dateString)")
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let date = formatter.dateFromString(dateString)
println("date: \(date)")
formatter.dateFormat = "yyyy-MM-dd"
let formattedDateString = formatter.stringFromDate(date!)
println("formattedDateString: \(formattedDateString)")
Output :
dateString: 2016-04-02
date: Optional(2016-04-01 21:00:00 +0000)
formattedDateString: 2016-04-02
2016-04-01 21:00:00 +0000
I am trying to convert a string to NSDate datatype but not getting correct value. I have tried many solutions but its not returning correct value. I need it in yyyy-MM-dd format (2016-04-02) same as my input "2016-04-02". If someone can help would be really apriciated. Thanks in advance
I had the same problem and i this worked for me
You need to set the time zone
formatter.timeZone = NSTimeZone(abbreviation: "GMT+0:00")
When you convert from string to NSDate, if you do not set the timezone to the formatter, you will get the NSDate of a date in your local time zone. I suppose that your time zone is GMT+3 .
Then, when you show the value of 'date' (using println, NSLog but not NSDateFormatter), without setting the time zone, you will get GMT+0 time. That why you got 3h later.
Depend on how to use NSDateFormatter, you will have the date string as you want. In your case, It returns what you want, doesn't it?
Remember that NSDate presents a moment of time.
let dateString = "2016-04-02"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
println("dateString: \(dateString)")
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let date = formatter.dateFromString(dateString) //without specify timezone, your dateString "2016-04-02" is your local time (GMT-3),
//means it's 2016-04-02 00:00:000 at GMT+0. That is the value that NSDate holds.
println("date: \(date)") //that why it show 2016-04-01 21:00:000, but not 2016-04-02 00:00:000
formatter.dateFormat = "yyyy-MM-dd"
let formattedDateString = formatter.stringFromDate(date!)
println("formattedDateString: \(formattedDateString)")
Your date is perfectly good. :-) No pun intended.
I will elaborate more on what #HoaParis has answered.
First of all NSDate represents a moment in time. It is not a date time value at the given place. So NSDate representing midnight in Greenwich will be 5:30 in morning in India.
Now coming to your question. When you give a date format with out time the formatter will assume it to be mid night. Also if there is not timezone mentioned it will take the current time zone.
So '2016-04-02' represents '2016-04-02, 00:00:00' at your time zone. Your timezone is GMT+3 that means when it is midnight at your place it is still 21:00:00 hours of previous day at Greenwich i.e. UK.
As we discussed NSDate is a moment in time to the same NSDate object represents these two seemingly different times but in reality they are the same time moment.
When you print the date by default it will print the date with respect to GMT and not your time zone i.e 2016-04-01, 21:00:00. The formatter will take into account your time zone and make it '2016-04-02'
let dateFormatter = DateFormatter()
//Your current Date Format
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let finaldate = dateFormatter.date(from:"Your String")
//Your changing Date Format
dateFormatter.dateFormat = "MMM-dd"
let second = dateFormatter.string(from: finaldate!)

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.