Basic use of time-related Nscalendar and NSDate classes

Source: Internet
Author: User
Tags date1

1. Resolving the time to get NSDate is incorrect

NSDate *nowdate = [NSDate Date];

Nstimezone *localtimezone = [Nstimezone localtimezone];
Nsinteger ti = [Localtimezone secondsfromgmtfordate:nowdate];

NSDate *newdate = [Nowdate Datebyaddingtimeinterval:ti];
NSLog (@ "World unification Time:%@ local time:%@", Nowdate, newdate);

1.获取当前时间的年月日时分秒

Nscalendar *calendar = [Nscalendar Currentcalendar];

Nscalendarunit unit = Nscalendarunityear | Nscalendarunitmonth | Nscalendarunitday | Nscalendarunithour | Nscalendarunitminute | Nscalendarunitsecond;

nsdatecomponents *components = [Calendar components:unit fromdate:[nsdate Date]];

NSLog (@ "Year:%ld months:%ld days:%ld:%ld:%ld seconds:%ld", (Long) components.year, (Long) components.month, (Long) Components.day, ( Long) Components.hour, (Long) Components.minute, (long) components.second);

2.比较两个时间之间的差值

NSDate *date1 = [NSDate Date]; The current date

NSString *datestr = @ "2015-06-29 07:05:26 +0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
Formatter.dateformat = @ "Yyyy-mm-dd HH:mm:ss Z";
NSDate *date2 = [Formatter datefromstring:datestr]; The specified date

Nscalendar *calendar = [Nscalendar Currentcalendar];
Nscalendarunit unit = Nscalendarunityear | Nscalendarunitmonth | Nscalendarunitday | Nscalendarunithour | Nscalendarunitminute | Nscalendarunitsecond;
nsdatecomponents *components = [Calendar components:unit fromdate:date1 todate:date2 options:0];

NSLog (@ "Difference year:%ld months:%ld days:%ld:%ld:%ld seconds:%ld", (Long) components.year, (Long) components.month, (Long) Components.day, ( Long) Components.hour, (Long) Components.minute, (long) components.second);

Basic use of time-related Nscalendar and NSDate classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.