iOS:今天(和明天)的时间戳@0:00:00am

iOS: Timestamps from today (and tomorrow) @ 0:00:00am

我想创建一个从今天凌晨 0 点开始(以及明天)的时间戳。任何人都可以提供一些代码如何将其作为字符串获取吗?

给你。

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

今天早上要获取 12:00am,请使用 NSCalendar 获取日、月和年,然后使用这些日期组件(不包括时间)获取 NSDate:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:now];
NSDate *thisMorning = [calendar dateFromComponents:components];

要明天得到12:00am,加一天:

NSDate *tomorrowMorning = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:thisMorning options:0];

要将它们转换为字符串,请使用 NSDateFormatter

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateStyle = NSDateFormatterLongStyle;
formatter.timeStyle = NSDateFormatterLongStyle;

NSString *thisMorningString = [formatter stringFromDate:thisMorning];
NSString *tomorrowMorningString = [formatter stringFromDate:tomorrowMorning];

显然,使用您想要的任何 dateStyletimeStyle(或 dateFormat 字符串)。


如果你想要自 1970 年以来的秒数,那就是

NSTimeInterval thisMorningIntervalSince1970 = [thisMorning timeIntervalSince1970];
NSTimeInterval tomorrowMorningIntervalSince1970 = [tomorrowMorning timeIntervalSince1970];

如果您希望将它们作为字符串,可以是:

NSString *thisMorningTimeIntervalString = [NSString stringWithFormat:@"%f", thisMorningIntervalSince1970];
NSString *tomorrowMorningTimeIntervalString = [NSString stringWithFormat:@"%f", tomorrowMorningIntervalSince1970];

NSString *thisMorningTimeIntervalString = [NSString stringWithFormat:@"%lld", (long long) thisMorningIntervalSince1970];
NSString *tomorrowMorningTimeIntervalString = [NSString stringWithFormat:@"%lld", (long long) tomorrowMorningIntervalSince1970];