我想从今天凌晨0点开始创建一个时间戳(明天)。任何人都可以提供一些代码,我怎么能把它作为一个字符串?
答案 0 :(得分:1)
你有。
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]];
答案 1 :(得分:1)
要在今天早上12:00到达,请使用NSCalendar
获取日,月和年,然后使用这些日期组件(不包括时间)来获取NSDate
:< / p>
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];