【发布时间】:2015-04-14 15:15:31
【问题描述】:
我想从今天凌晨 0 点(以及明天)创建一个时间戳。任何人都可以提供一些代码如何将其作为字符串获取吗?
【问题讨论】:
标签: objective-c timestamp nsdate
我想从今天凌晨 0 点(以及明天)创建一个时间戳。任何人都可以提供一些代码如何将其作为字符串获取吗?
【问题讨论】:
标签: objective-c timestamp nsdate
要获得今天上午 12:00,请使用 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:00,请添加一天:
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];
显然,使用您想要的任何 dateStyle 和 timeStyle(或 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];
【讨论】:
给你。
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]];
【讨论】: