thieumao

Date to String

Feb 23rd, 2017
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.15 KB | None | 0 0
  1. //
  2. //  ViewController.swift
  3. //  TestThu
  4. //
  5. //  Created by Nguyen Van Thieu B on 2/23/17.
  6. //  Copyright © 2017 Thieu Mao. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. class ViewController: UIViewController {
  12.  
  13.     override func viewDidLoad() {
  14.         super.viewDidLoad()
  15.         let timeInterval = 1514156400.0
  16.         print("timeInterval ", timeInterval)
  17.         let date = Date(timeIntervalSince1970: timeInterval)
  18.         print("date ", date)
  19.         print("date.toDateString ", date.toDateString())
  20.        
  21.         let now = Date();
  22.         let coms = now.components()
  23.        
  24.         print("now.toDateString ", String(format: "%04d/%02d/%02d", coms.2!, coms.1!, coms.0!))
  25.        
  26.         let now2 = NSDate()                         // "Aug 25, 2015, 2:56 PM"
  27.         print("now2", now2.toString(format: "yyyy-MM-dd HH:mm:ss"))
  28.        
  29.         let now3 = Date();
  30.         if #available(iOS 10.0, *) {
  31.             print("now3.toDateString2 ", now.toDateString2())
  32.         } else {
  33.             // Fallback on earlier versions
  34.         }
  35.     }
  36.  
  37. }
  38.  
  39. extension Date {
  40.     func toDateString() -> String {
  41.         let dateFormatter = DateFormatter()
  42.         dateFormatter.dateFormat = "MM-dd-yyyy"//"yyyy/MM/dd"
  43.         return dateFormatter.string(from: self);
  44.     }
  45.    
  46.     func components() -> (Int?, Int?, Int?, Int?, Int?, Int?) {
  47.         let dateComponents = Calendar.current.dateComponents([.day, .month, .year, .hour, .minute, .second], from: self)
  48.         return (dateComponents.day, dateComponents.month, dateComponents.year, dateComponents.hour, dateComponents.minute, dateComponents.second)
  49.     }
  50.    
  51.     @available(iOS 10.0, *)
  52.     func toDateString2() -> String {
  53.         let dateFormatter = ISO8601DateFormatter()
  54.         dateFormatter.date(from: "MM-dd-yyyy")
  55. //        dateFormatter.dateFormat = "MM-dd-yyyy"//"yyyy/MM/dd"
  56.         return dateFormatter.string(from: self);
  57.     }
  58.    
  59. }
  60.  
  61. extension NSDate {
  62.     // Instance Method
  63.     func toString(format: String) -> String {
  64.         let dateFormatter = DateFormatter()
  65.         dateFormatter.dateFormat = format
  66.         return dateFormatter.string(from: self as Date)
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment