简体   繁体   English

将NSDate转换为另一种格式

[英]Convert NSDate to another format

I have an NSDate that logs to console (on my machine with my settings) like this: 我有一个NSDate可以这样登录到控制台(在我的机器上使用我的设置):

2015-12-30 18:10:27 +0000 2015-12-30 18:10:27 +0000

How would I convert it to a string that I can store on a remote server like this? 我如何将其转换为可存储在这样的远程服务器上的字符串?

2015-12-30 18:10:27 2015-12-30 18:10:27

Since the server must serve multiple clients, it is important that the dates on it always be in a consistent format. 由于服务器必须为多个客户端提供服务,因此,服务器上的日期必须始终保持一致的格式非常重要。

My understanding is that NSFormatter uses local settings that vary by client so I cannot rely on it to always provide the same string format for saving on a server so therefore I am at a loss: 我的理解是NSFormatter使用的本地设置因客户端而异,因此我不能依靠它始终提供相同的字符串格式来保存在服务器上,因此我感到茫然:

Here is code I have so far: 这是我到目前为止的代码:

    NSDate *date = self.datePicker.date;
    NSLog(@"date is:%@",date); //logs as above => 2015-12-30 18:10:27 +0000
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSString *datestring = [dateFormatter stringFromDate:date];
NSLog(@"datestring%@",datestring); //logs => 2015-12-30T13:10:27.000Z

This is not quite what I want and I'm also not confident this will always create the same format on different handhelds for saving on a server. 这不是我想要的,我也不相信它将始终在不同的手持设备上创建相同的格式以保存在服务器上。

Would appreciate any suggestions. 将不胜感激任何建议。

You can use UNIX timestamp: 您可以使用UNIX时间戳:

NSString *timestamp = [NSString stringWithFormat:@"%f",[date timeIntervalSince1970] * 1000];

Or you can set custom date format of your NSDateFormatter: 或者,您可以设置NSDateFormatter的自定义日期格式:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
NSString *datestring = [dateFormatter stringFromDate:date];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM