问题
So my dilemma is that I can't figure out how to store the date only in an integer value (fetched using:
NSDate* date = [NSDate date]
I found this code online which seems similar to what I need (I thought that changing setDateFormat to @"dd" would've worked (but apparently it didn't)
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
//Optionally for time zone conversions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
NSString *stringFromDate = [formatter stringFromDate:date];
Am I just forgetting something simple about integers?
回答1:
Use dd
in setDateFormat:
.
This will give only date but in string.
After this you can convert the string to integer, with the help of integerValue
.
Edit:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd"];
NSString *stringFromDate = [formatter stringFromDate:[NSDate date]];
NSInteger integerDate = [stringFromDate integerValue];
回答2:
Swift
NSDate
to Int
// using current date and time as an example
let someNSDate = NSDate()
// convert NSDate to NSTimeInterval (typealias for Double)
let timeInterval = someNSDate.timeIntervalSince1970
// convert to Integer
let myInt = Int(timeInterval)
Doing the Double
to Int
conversion causes the milliseconds to be lost. If you need the milliseconds then multiply by 1000 before converting to Int
.
Int
to NSDate
Including the reverse for completeness.
// convert Int to Double
let timeInterval = Double(myInt)
// create NSDate from Double (NSTimeInterval)
let myNSDate = NSDate(timeIntervalSince1970: timeInterval)
I could have also used timeIntervalSinceReferenceDate
instead of timeIntervalSince1970
as long as I was consistent. This is assuming that the time interval is in seconds. Note that Java uses milliseconds.
Update
As of Swift 3, the conversion would use Date
rather than NSDate
. See this answer for the Swift 3 version.
回答3:
Although I believe the original poster was looking for just the 'days' part of the date, I imagine that given the title, others will come to this question looking for a way to convert a date to a canonical integer representation (for example, milliseconds since the epoch).
The Cocoa date library stores dates as a floating point number of seconds since 00:00:00 UTC on 1 January 2001
.
To get this value, call [NSDate timeIntervalSinceReferenceDate]
. To get the number of seconds (floating point) since the Unix epoch, call [NSDate timeIntervalSince1970]
. To get milliseconds, simply multiply by 1000.
So, to get the number of milliseconds since the Unix epoch, as an integer:
(NSInteger)round([NSDate timeIntervalSince1970] * 1000)
来源:https://stackoverflow.com/questions/27059292/convert-nsdate-to-an-integer