简体   繁体   English

Xcode-从服务器(例如time.is)获取当前日期和时间,并将其转换为NSDate

[英]Xcode - Get Current date and time from a server(like time.is) and convert it to NSDate

i don't want to get the current date from the users device, because the user can edit the date. 我不想从用户设备获取当前日期,因为用户可以编辑日期。

i would like to get the current date and time from a server like time.apple.com or time.is and then convert it to an NSDate. 我想从类似time.apple.com或time.is的服务器获取当前日期和时间,然后将其转换为NSDate。 How? 怎么样?

You can first get the date in the form of a string by hitting the url (if the webservice is giving it as a string). 您可以通过点击url(如果网络服务以字符串形式提供)来首先以字符串形式获取日期。 And then using date formatter you could make the string into an NSDate . 然后使用日期格式化程序,可以将字符串转换为NSDate

For instance: 例如:

NSURL *url = [NSURL URLWithString:@"http://yourtimeurl"];
NSString *str = [[NSString alloc] initWithContentsOfURL:url usedEncoding:Nil error:Nil];

assume you are getting the date in the format dd-MM-yyyy, then 假设您以dd-MM-yyyy格式获取日期,则

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat =@"dd-MM-yyyy";
NSDate *date = [dateFormatter dateFromString:str];

But most probably when you hit your url, you might get some data structure like a json which you would have to parse. 但是最有可能的是,当您点击URL时,您可能会得到一些诸如json之类的数据结构,您必须对其进行解析。 And most probably the date wouldn't be returned in the above format. 而且很可能不会以上述格式返回日期。 But now you know how to go forward. 但是现在您知道如何前进了。 Make the appropriate changes. 进行适当的更改。

Also initWithContentsOfURL: is a synchronous call. 另外, initWithContentsOfURL:是一个同步调用。 It's recommended that you use a NSURLConnection for this and make asynch call to your webservice. 建议为此使用NSURLConnection并异步调用您的Web服务。

This might be useful: http://www.earthtools.org/webservices.htm#timezone --xmlresponse 这可能会很有用: http : //www.earthtools.org/webservices.htm#timezone --xmlresponse
http://www.timeapi.org/utc/now --string http://www.timeapi.org/utc/now --string

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

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