将 NSString 转换为具有日期格式的 NSString 块

发布于 2024-08-22 03:24:22 字数 209 浏览 3 评论 0原文

这可能很简单。我已经搜索过了,还没找到。

如何将 NSString @"20100216190205" 转换为格式 @"yyyy-MM-dd HH:mm:ss" 的 NSString。

即:@“2010-02-16 19:02:05”

编辑: 对于其他情况,我想避免使用 NSDateFormatter 来使其更加通用。

This might be simple. I have searched, not found yet.

How do I convert the NSString @"20100216190205" to an NSString of format @"yyyy-MM-dd HH:mm:ss".

ie: @"2010-02-16 19:02:05"

EDIT:
I wanted to avoid using the NSDateFormatter to be more generic, for other situations.

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

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

发布评论

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

评论(3

看轻我的陪伴 2024-08-29 03:24:22

您可以提取每个子字符串,将它们转换为整数 (-intValue),然后使用 NSDateComponents 将它们转换为日期。而且比使用NSDateFormatter麻烦很多。

在您的情况下,在调用 -dateFromString: 之前,需要将 NSDateFormatter 的格式设置为 yyyyMMddHHmmss ,即

[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSDate *date = [formatter dateFromString:@"20100216190205"];
....

You can extract each substring, convert them into integers (-intValue), then use NSDateComponents to convert these into a date. And it is much more troublesome than using NSDateFormatter.

In your case, the NSDateFormatter's format needs to be set to yyyyMMddHHmmss before calling -dateFromString:, i.e.

[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSDate *date = [formatter dateFromString:@"20100216190205"];
....
凡间太子 2024-08-29 03:24:22

纯粹作为编写代码的练习:

NSString* digits = @"20100216190205"; // this is probably a parameter somewhere
NSMutableString* formatted = [digits mutableCopy];
[formatted insertString:@":" atIndex:12];
[formatted insertString:@":" atIndex:10];
[formatted insertString:@" " atIndex:8];
[formatted insertString:@"-" atIndex:6];
[formatted insertString:@"-" atIndex:4];
NSLog(@"original string: %@ -> formatted: %@", digits, formatted);

但我同意:对自己放轻松,并为此使用日期格式化程序。

Purely as an exercise in writing code:

NSString* digits = @"20100216190205"; // this is probably a parameter somewhere
NSMutableString* formatted = [digits mutableCopy];
[formatted insertString:@":" atIndex:12];
[formatted insertString:@":" atIndex:10];
[formatted insertString:@" " atIndex:8];
[formatted insertString:@"-" atIndex:6];
[formatted insertString:@"-" atIndex:4];
NSLog(@"original string: %@ -> formatted: %@", digits, formatted);

But I agree: go easy on yourself, and use a date formatter for this.

指尖上的星空 2024-08-29 03:24:22

您需要将格式化程序的格式设置为 yyyyMMddHHmmss 才能解析示例中的字符串。您需要创建一个新的格式化程序或修改原始格式化程序的格式以合并您想要的更具视觉吸引力的格式 (@"yyyy-MM-dd HH:mm:ss")。

You'll need to set your formatter's format to yyyyMMddHHmmss to parse the string you have in your example. You'll need to either create a new formatter or modify the original formatter's format to incorporate the more visually appealing one that you want (@"yyyy-MM-dd HH:mm:ss").

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