【问题标题】:iOS: Timestamps from today (and tomorrow) @ 0:00:00am [duplicate]iOS:今天(和明天)@ 0:00:00am 的时间戳 [重复]
【发布时间】:2015-04-14 15:15:31
【问题描述】:

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

【问题讨论】:

    标签: objective-c timestamp nsdate


    【解决方案1】:

    要获得今天上午 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];
    

    显然,使用您想要的任何 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];
    

    【讨论】:

      【解决方案2】:

      给你。

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

      【讨论】:

      • 我想要一个时间戳(自 1970 年以来的日期,以秒为单位)
      • 不错!以及如何使用日期而不是设置字符串?
      • 谢谢,我没有意识到。
      • @Tim 是的,当然你可以使用日期。如果您想查看如何在没有 NSString 的情况下对日期收费,请查看 Rob 的帖子。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      相关资源
      最近更新 更多