从日期格式中删除时间

发布于 2024-09-04 03:55:08 字数 277 浏览 6 评论 0原文

我正在开发一个应用程序,我使用 DatePicker 来选择日期,但它给了我日期和时间。我已将该格式转换为字符串,现在我只想要其中的日期。我该怎么做。请给我建议。

以下是我的代码片段。

  NSDate *selected =[datePicker date];
  NSString *dateString = [NSString stringWithFormat:@"%@", selected];

这里日期选择器是 UIDatePicker 的对象。

I am developing an application in that i have used DatePicker to pick the date but it gives me date with time .I have converted that format into string, now i just want date from that. How should i do that.Plz suggest me something.

Following is my code Snippet.

  NSDate *selected =[datePicker date];
  NSString *dateString = [NSString stringWithFormat:@"%@", selected];

here date picker is object of UIDatePicker.

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

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

发布评论

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

评论(2

2024-09-11 03:55:08

您可以使用 NSCalendar 获取日期的月、日和年部分,对其进行操作并重新组合它们。这是一些示例代码。

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:date];

[otherDateComponents setYear:[dateComponents year]];
[otherDateComponents setMonth:[dateComponents month]];
[otherDateComponents setDay:[dateComponents day]];

NSDate *newDate = [calendar dateFromComponents:otherDateComponents];

请注意,由于当前日历是特定于区域设置的,因此您返回的值在所有设备上都不会相同。您可能希望根据您的目的指定特定的日历。 NSGregorianCalendar 是西方最常用的一种。

You can use NSCalendar to get the month, day, and year components of your date, manipulate them, and reassemble them. Here's some example code.

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:date];

[otherDateComponents setYear:[dateComponents year]];
[otherDateComponents setMonth:[dateComponents month]];
[otherDateComponents setDay:[dateComponents day]];

NSDate *newDate = [calendar dateFromComponents:otherDateComponents];

Be aware that since the current calendar is locale-specific, the values you get back will not be the same on all devices. You may wish to specify a particular calendar for your purposes. NSGregorianCalendar is the one most often used in the west.

征﹌骨岁月お 2024-09-11 03:55:08

这是另一个解决方案:

NSDate *selected =[datePicker date];
NSDateFormatter *formatter = [NSDateFormatter new];

[formatter setDateStyle:NSDateFormatterMediumStyle];
NSDate *day = [formatter dateFromString:[formatter stringFromDate:selected]];
[formatter release];

Here is another solution:

NSDate *selected =[datePicker date];
NSDateFormatter *formatter = [NSDateFormatter new];

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