• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Swift之数据类型:时间日期

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

2017.05.22 18:17* 字数 212 阅读 644评论 0喜欢 0

时间日期

 

NSDate

在OC中,可以使用如下的代码创建一个UTC的时间:

NSDate *currentUTCDate = [NSDate date]

但在Swift中,使用 let date = NSDate()

获取到的则是本地时间。

UTC时间与本地化时间

let date = NSDate();

// "Apr 1, 2015, 8:53 AM" <-- local without seconds

 

var formatter = NSDateFormatter();

formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ";

let defaultTimeZoneStr = formatter.stringFromDate(date);

// "2015-04-01 08:52:00 -0400" <-- same date, local, but with seconds

formatter.timeZone = NSTimeZone(abbreviation: "UTC");

let utcTimeZoneStr = formatter.stringFromDate(date);

// "2015-04-01 12:52:00 +0000" <-- same date, now in UTC

时间比较

如果需要比较两个日期,可以使用如下方法,在如下代码中已经展示了如何处理不同的返回结果:

// Date comparision to compare current date and end date.

var dateComparisionResult:NSComparisonResult = NSDate().compare(endDate)

 

if dateComparisionResult == NSComparisonResult.OrderedAscending

{

// Current date is smaller than end date.

}

else if dateComparisionResult == NSComparisonResult.OrderedDescending

{

// Current date is greater than end date.

}

else if dateComparisionResult == NSComparisonResult.OrderedSame

{

// Current date and end date are same.

}

TimeStamp

如果需要将某个TimeStamp("/Date(1427909016000-0800)”)转化为NSDate对象,那么可以使用如下的扩展工具,该扩展将会把TimeStamp转化为本地化时间。其中1427909016000表示从Unix计时以来的毫秒数,而-0800表示时区:

/// Swift3的写法

extension NSDate {

    convenience init?(jsonDate: String) {

        let prefix = "/Date("

        let suffix = ")/"

        let scanner = Scanner(string: jsonDate)

        

        // Check prefix:

        if scanner.scanString(prefix, into: nil) {

            

            // Read milliseconds part:

            var milliseconds : Int64 = 0

            if scanner.scanInt64(&milliseconds) {

                // Milliseconds to seconds:

                var timeStamp = TimeInterval(milliseconds)/1000.0

                

                // Read optional timezone part:

                var timeZoneOffset : Int = 0

                if scanner.scanInt(&timeZoneOffset) {

                    let hours = timeZoneOffset / 100

                    let minutes = timeZoneOffset % 100

                    // Adjust timestamp according to timezone:

                    timeStamp += TimeInterval(3600 * hours + 60 * minutes)

                }

                

                // Check suffix:

                if scanner.scanString(suffix, into: nil) {

                    // Success! Create NSDate and return.

                    self.init(timeIntervalSince1970: timeStamp)

                    return

                }

            }

        }

        

        // Wrong format, return nil. (The compiler requires us to

        // do an initialization first.)

        self.init(timeIntervalSince1970: 0)

        return nil

    }

}

使用的例子如下:

    if let theDate = NSDate(jsonDate: "/Date(1427909016000-0800)/") {

        println(theDate)

    } else {

        print("错误的格式")

    }

 

NSDateFormatter:格式化时间

    var dataString = "April 1, 2015" as String

    var dateFormatter = NSDateFormatter()

    dateFormatter.dateFormat = "MM-dd-yyyy"

    dateFormatter.timeZone = NSTimeZone.localTimeZone()

    

    // convert string into date

    let dateValue = dateFormatter.dateFromString(dataString) as NSDate!

    

    print(dateValue)

 

NSCalendar 日历

// Setup the calendar object

let calendar = NSCalendar.currentCalendar()

 

// Set up date object

let date = NSDate()

 

// Create an NSDate for the first and last day of the month

//let components = calendar.components(NSCalendarUnit.CalendarUnitYear |

//                                     NSCalendarUnit.CalendarUnitMonth |

//                                     NSCalendarUnit.WeekdayCalendarUnit |

//                                     NSCalendarUnit.WeekCalendarUnit |

//                                     NSCalendarUnit.CalendarUnitDay,

//                                     fromDate: date)

 

// Create an NSDate for the first and last day of the month

let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: date)

 

 

components.month

 

// Getting the First and Last date of the month

components.day = 1

let firstDateOfMonth: NSDate = calendar.dateFromComponents(components)!

 

components.month  += 1

components.day     = 0

let lastDateOfMonth: NSDate = calendar.dateFromComponents(components)!

 

var unitFlags = NSCalendarUnit.WeekOfMonthCalendarUnit |

    NSCalendarUnit.WeekdayCalendarUnit     |

    NSCalendarUnit.CalendarUnitDay

 

let firstDateComponents = calendar.components(unitFlags, fromDate: firstDateOfMonth)

let lastDateComponents  = calendar.components(unitFlags, fromDate: lastDateOfMonth)

 

// Sun = 1, Sat = 7

let firstWeek = firstDateComponents.weekOfMonth

let lastWeek  = lastDateComponents.weekOfMonth

 

let numOfDatesToPrepend = firstDateComponents.weekday - 1

let numOfDatesToAppend  = 7 - lastDateComponents.weekday + (6 - lastDateComponents.weekOfMonth) * 7

 

let startDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -numOfDatesToPrepend, toDate: firstDateOfMonth, options: nil)!

let endDate:   NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: numOfDatesToAppend, toDate: lastDateOfMonth, options: nil)!

 

Array(map(0..<42) {

calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: $0, toDate: startDate, options: nil)!

})

 

"\(components.year)"

 

 

var dateString = "2014-10-3" // change to your date format

var dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "YYYY-MM-dd"

 

var someDate = dateFormatter.dateFromString(dateString)

print(someDate)

 

 

17_articlex.png

文章参考:https://segmentfault.com/a/1190000003742865


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap