gpt4 book ai didi

ios - 从日期字符串开始的 24 小时时间

转载 作者:可可西里 更新时间:2023-11-01 04:41:14 26 4
gpt4 key购买 nike

我正在尝试从以下字符串中以 24 小时格式获取时间和时间:

2015 年 7 月 2 日下午 2:30:00

这是我试过的:

-(NSString*)returnDate:(NSString*)dateString
{

NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"MM/dd/yyyy hh:mm:ss aaa"];
NSDate *date = [dateFormatter1 dateFromString:dateString];

dateString = [date descriptionWithLocale:[NSLocale systemLocale]];



NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;

NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date];

NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:@"HH:mm a"];
[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateString = [dateFormatters stringFromDate: destinationDate];

return dateString;
}

输出:4:30

这是返回正确的时间,但采用 12 小时格式。我想要 24 小时格式的时间。

期望的输出:16:30

最佳答案

问题中有很多代码,试试这个:

NSString *dateString = @"7/2/2015 4:30:00 PM";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss aaa"];
NSDate *date = [dateFormatter dateFromString:dateString];

[dateFormatter setDateFormat:@"HH:mm"];
dateString = [dateFormatter stringFromDate: date];

NSLog(@"dateString: %@", dateString);

输出:

dateString: 16:30

关于ios - 从日期字符串开始的 24 小时时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31231181/

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