gpt4 book ai didi

ios - 从当前日期创建时如何获取日期值

转载 作者:行者123 更新时间:2023-11-29 11:53:21 24 4
gpt4 key购买 nike

如何转换字符串日期@"2016-10-19T12:37:15.0896144+00:00"int second/Min/hour/days/months/year.

我有日期创造值(value),即@"2016-10-19T12:37:15.0896144+00:00"

**几秒钟后需要显示“50 秒”

几分钟后需要显示“40 分钟”

几个小时后需要显示@"20 小时"

几天后需要显示@"3 天"

几个月后需要显示@"4 个月"

几年后需要显示@"2 years"**

我试过的是我没有工作。

NSString* format = @"2016-10-19T12:37:15.0896144+00:00";
// Set up an NSDateFormatter for UTC time zone
NSDateFormatter* formatterUtc = [[NSDateFormatter alloc] init];
[formatterUtc setDateFormat:format];
[formatterUtc setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Cast the input string to NSDate
NSDate* utcDate = [formatterUtc dateFromString:[formatterUtc stringFromDate:timeString]];

// Set up an NSDateFormatter for the device's local time zone
NSDateFormatter* formatterLocal = [[NSDateFormatter alloc] init];
[formatterLocal setDateFormat:format];
[formatterLocal setTimeZone:[NSTimeZone localTimeZone]];
// Create local NSDate with time zone difference
NSDate* localDate = [formatterUtc dateFromString:[formatterLocal stringFromDate:utcDate]];
NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate:localDate];

非常感谢您的意见。

最佳答案

使用 NSDateFormatter 将字符串转换为日期。然后使用 NSDateComponentsFormattermaximumUnitCount 为 1,allowedUnits 包括秒、分钟、小时、天、月和年。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

NSDate *date1 = [dateFormatter dateFromString:@"2016-08-19T12:37:15.0896144+00:00"];
NSDate *date2 = [NSDate date]; // or, if date2 is also from a string, just use that dateFormatter again

NSDateComponentsFormatter *componentsFormatter = [[NSDateComponentsFormatter alloc] init];
componentsFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
componentsFormatter.allowedUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
componentsFormatter.maximumUnitCount = 1;

NSString *string = [componentsFormatter stringFromDate:date1 toDate:date2];

如果您想了解 locale 设置,请参阅 Apple Technical Q&A 1480 .

关于ios - 从当前日期创建时如何获取日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com