Home  >  Q&A  >  body text

objective-c - ios 如何获取当天6点的时间戳

如题
如何获取当天某一时刻的时间戳呢?

PHP中文网PHP中文网2741 days ago251

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 18:00:14

    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [greCalendar setTimeZone: timeZone];
    
    NSDateComponents *dateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit  fromDate:[NSDate date]];
    
    //  定义一个NSDateComponents对象,设置一个时间点
    NSDateComponents *dateComponentsForDate = [[NSDateComponents alloc] init];
    [dateComponentsForDate setDay:dateComponents.day];
    [dateComponentsForDate setMonth:dateComponents.month];
    [dateComponentsForDate setYear:dateComponents.year];
    [dateComponentsForDate setHour:23];
    [dateComponentsForDate setMinute:59];
    
    NSDate *dateFromDateComponentsForDate = [greCalendar dateFromComponents:dateComponentsForDate];
    return dateFromDateComponentsForDate;
    

    This is to get 23:59 minutes in the Beijing time zone of the day. You just need to modify the time you want to get. For the timestamp, just change the time zone to zero time zone. Can this solve your problem?

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 18:00:14

    Hello, the method you mentioned cannot get the date of 23:59 in the Beijing time zone of the day. Although you have set the time zone, and set the hours and minutes, you still cannot get the date of 0:00 and 23:59 of the day. Date and time, if there is anything wrong with my own use of your code, please point it out, thank you

    The method I found later is: No need to set the time zone, just set the hour to 8 hours, so that you can get

    // 创建日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
        
        // 初始化日历组件
        NSDateComponents *dateComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
        
        [dateComponents setYear:dateComponents.year];
        [dateComponents setMonth:dateComponents.month];
        [dateComponents setDay:dateComponents.day];
        [dateComponents setHour:8];    // 设置为为8 时
        
        NSDate *timeDate = [calendar dateFromComponents:dateComponents];
        
        // 从0 点开始24 小时之后的时间
        NSDate *end = [timeDate dateByAddingTimeInterval:24 * 3600];
        
        WZLog(@"获取的时间为 = %@", timeDate);

    Hello, your method is correct. What I said only shows the current correct time. After converting it to a timestamp, it is actually not correct. Sorry, I made a mistake

    reply
    0
  • Cancelreply