Using Swift to operate the NSDate type base

Source: Internet
Author: User

The time type is a data type that we use very frequently when we are dealing with the business. Let's take a look at the basic use of time nsdate.

1. Compare size

I'm better at. NET, and we know that a datetime type in C # can be directly judged using ">" "<" = ". But nsdate in Swift does not support the way this comparison is. We need to use the Nsdate.compare method to compare. Nsdate.compare returns an enumeration of Nscomparisonresult. This enumeration consists of 3 values:

Nscomparisonresult. orderedascending//Time Ascending

Nscomparisonresult. orderedsame//same

Nscomparisonresult. ordereddescending//time Reverse

where NSDate () returns the current time by default. So the time value of Date2 is certainly bigger than date1. If you want to implement C # using ">" < "=" to compare time, you can use the above method to overload the operator.

2. Calculate the time difference

We know that in C # you can subtract the datetime type directly, and the result is a time difference. So how is it done in Swift? We use

Nscalendar. Currentcalendar(). Components come in between 2 time intervals. The method returns an object of type nsdatecomponents. The Nsdatecomponents object represents a period of time and is described in a way that is easier for us to read:

3. Construction time

sometimes we need to construct a time for ourselves. is actually the above Datepare method. We can specify the year date to construct a nsdatecomponents and then use Nscalendar. Datefromcomponents method to construct a time.

The above is almost the most basic usage of nsdate in Swift.

Using Swift to operate the NSDate type base

Related Article

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.