-1

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?

Tim
  • 175
  • 1
  • 1
  • 12

2 Answers2

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
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