objective-c - ios 如何获取当天6点的时间戳
PHP中文网
PHP中文网 2017-04-17 17:58:14
0
2
244

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

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
黄舟
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?

Peter_Zhu

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!