如何查找存储在2个字符串中的日期之间的天数

发布于 2024-10-25 13:01:01 字数 116 浏览 2 评论 0原文

我有两个字符串都采用以下日期格式(2011-03-22)。
我必须比较它们并找出它们之间的天数。

谁能告诉我如何做到这一点..

还请告诉我将它们转换回 NSDate 的正确方法。

I have two strings both are in following date format (2011-03-22).
i have to compare them and find number of days between them.

Can anyone tell me how to do this..

Please also tell me the correct method to convert them back to NSDate.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奢欲 2024-11-01 13:01:01

我刚刚输入的内容可能有几个错误,但它本身就说明了问题,您应该明白了。

NSString *dateStringA = @"2011-03-22";

NSString *dateStringB = @"2011-03-27";

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = @"yyyy-MM-dd";

NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];

NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates


NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them

Might be a couple of errors as i just typed this, but it speaks for itself and you should get the idea.

NSString *dateStringA = @"2011-03-22";

NSString *dateStringB = @"2011-03-27";

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = @"yyyy-MM-dd";

NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];

NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates


NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them
只想待在家 2024-11-01 13:01:01

对于字符串到日期

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];

对于日期到字符串

NSString *date = [[NSDate date] description];

 For string to date

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];

for date to string

NSString *date = [[NSDate date] description];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文