zoukankan      html  css  js  c++  java
  • [Xcode 实际操作]九、实用进阶-(4)计算两个日期间的差值

    目录:[Swift]Xcode实际操作

    本文将演示如何计算两个日期之间的差值。

    在项目导航区,打开视图控制器的代码文件【ViewController.swift】

     1 import UIKit
     2 
     3 class ViewController: UIViewController {
     4 
     5     override func viewDidLoad() {
     6         super.viewDidLoad()
     7         // Do any additional setup after loading the view, typically from a nib.
     8         
     9         //创建第一个日期对象,其值为当前设备的时间
    10         let dateA = Date()
    11         //创建第二个日期对象,自定义它的时间
    12         let dateB = Date(timeInterval: -60*60*24*1000, since: Date())
    13         
    14         //判断设备的版本号是否在8以上,以执行后面的代码
    15         if #available(iOS 8.0, *)
    16         {
    17             //初始化一个日历对象,
    18             //日历对象通常用于处理与时间相关的问题。
    19             //比如比较时间的前后,计算日期间差别等。
    20             //日历对象支持多种历法,这里采用阳历。
    21             let calendar = NSCalendar(identifier: NSCalendar.Identifier.gregorian)
    22             //根据两个时间点,定义一个日期组件对象,
    23             //从而快速获得这两个时间点的差值
    24             let components = calendar?.components([NSCalendar.Unit.year,NSCalendar.Unit.month,NSCalendar.Unit.day], from: dateA, to: dateB, options: NSCalendar.Options.matchFirst)
    25         
    26             //在控制台打印输出两个日期相差的天数
    27             print("Day:(String(describing: components?.day))")
    28             //在控制台打印输出两个日期相差的月数
    29             print("Month:(String(describing: components?.month))")
    30             //在控制台打印输出两个日期相差的年数
    31             print("Year:(String(describing: components?.year))")
    32         }
    33     }
    34 
    35     override func didReceiveMemoryWarning() {
    36         super.didReceiveMemoryWarning()
    37         // Dispose of any resources that can be recreated.
    38     }
    39 }
  • 相关阅读:
    MATLAB新手教程
    关于Core Location-ios定位
    《TCP/IP具体解释卷2:实现》笔记--IP的分片和重装
    利用JasperReport+iReport进行Web报表开发
    Surface、SurfaceView、SurfaceHolder及SurfaceHolder.Callback之间的关系
    Openfire开发配置,Openfire源码配置,OpenFire二次开发配置
    在Activity中为什么要用managedQuery()
    24点经典算法
    linux概念之时间与时区
    java实现第五届蓝桥杯大衍数列
  • 原文地址:https://www.cnblogs.com/strengthen/p/10085217.html
Copyright © 2011-2022 走看看