I want to create a timestamp from today at 0 am (and for tomorrow). Can anybody give some code how I can get this as a string?
Asked
Active
Viewed 614 times
2 Answers
1
Here you have.
NSString * yourDate = @"2015-02-13 00:00:00";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate * date = [dateFormat dateFromString:yourDate];
NSString * timestamp = [NSString stringWithFormat:@"%f",[date timeIntervalSince1970]];

peig
- 418
- 3
- 11
-
I want a timestamp (the date in secs since 1970) – Tim Feb 13 '15 at 14:48
-
nice! and how can I use the date instead of a set string? – Tim Feb 13 '15 at 14:58
-
1Thank you, I didn't realize. – peig Feb 13 '15 at 15:05
-
@Tim Yes, of course you can use the date. If you want to check how to charge the date without an NSString check Rob's post. – peig Feb 13 '15 at 15:07
1
To get 12:00am this morning, use NSCalendar
to get day, month, and year, and then use those date components (which don't include time) to get a NSDate
:
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:now];
NSDate *thisMorning = [calendar dateFromComponents:components];
To get 12:00am tomorrow, add one day:
NSDate *tomorrowMorning = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:thisMorning options:0];
To convert these to strings, use NSDateFormatter
.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterLongStyle;
formatter.timeStyle = NSDateFormatterLongStyle;
NSString *thisMorningString = [formatter stringFromDate:thisMorning];
NSString *tomorrowMorningString = [formatter stringFromDate:tomorrowMorning];
Obviously, use whatever dateStyle
and timeStyle
(or dateFormat
string) that you want.
If you want the number of seconds since 1970, that would be
NSTimeInterval thisMorningIntervalSince1970 = [thisMorning timeIntervalSince1970];
NSTimeInterval tomorrowMorningIntervalSince1970 = [tomorrowMorning timeIntervalSince1970];
If you want those as strings, it would be either:
NSString *thisMorningTimeIntervalString = [NSString stringWithFormat:@"%f", thisMorningIntervalSince1970];
NSString *tomorrowMorningTimeIntervalString = [NSString stringWithFormat:@"%f", tomorrowMorningIntervalSince1970];
Or
NSString *thisMorningTimeIntervalString = [NSString stringWithFormat:@"%lld", (long long) thisMorningIntervalSince1970];
NSString *tomorrowMorningTimeIntervalString = [NSString stringWithFormat:@"%lld", (long long) tomorrowMorningIntervalSince1970];

Rob
- 415,655
- 72
- 787
- 1,044