美文网首页
SwiftDate使用笔记(翻译)

SwiftDate使用笔记(翻译)

作者: 39749980faf8 | 来源:发表于2018-07-12 16:29 被阅读254次

    SwiftDate新版本有一些重大更新,删除了原DateFormat,并且增加了一些新的东西。

    1、String转Date

    SwiftDate能够自动识别主流的时间格式(ISO8601, RSS, Alt RSS, .NET, SQL, HTTP...),你也可以手动指定格式。创建一个新的Date从未如此简单过。

    // All default datetime formats (15+) are recognized automatically
    let _ = "2010-05-20 15:30:00".toDate()
    // You can also provide your own format!
    let _ = "2010-05-20 15:30".toDate("yyyy-MM-dd HH:mm")
    // All ISO8601 variants are supported too with timezone parsing!
    let _ = "2017-09-17T11:59:29+02:00".toISODate()
    // RSS, Extended, HTTP, SQL, .NET and all the major variants are supported!
    let _ = "19 Nov 2015 22:20:40 +0100".toRSS(alt: true)
    

    2、Date操作

    可以通过使用自然语言添加或删除时间组件来操纵日期。时间扩展工具简单方便,而且支持常用的时区、日历、本地操作。
    可以使用标准数学运算符对日期、时间间隔、日期组件和相关时间单位之间进行操作!

    // Math operations support time units
    let _ = ("2010-05-20 15:30:00".toDate() + 3.months - 2.days)
    let _ = Date() + 3.hours
    let _ = date1 + [.year:1, .month:2, .hour:5]
    let _ = date1 + date2
    // extract single time unit components from date manipulation
    let over1Year = (date3 - date2).year > 1
    

    3、Date比较

    SwiftDate包含一组全面的比较函数;你可以按粒度比较两个日期,检查日期是否是某一天,某一范围以及您实际需要的任何其他比较。
    依然可以通过标准数学运算符(>,> =,<,<=)进行比较。

    // Standard math comparison is allowed
    let _ = dateA >= dateB || dateC < dateB
    
    // Complex comparisons includes granularity support
    let _ = dateA.compare(toDate: dateB, granularity: .hour) == .orderedSame
    let _ = dateA.isAfterDate(dateB, orEqual: true, granularity: .month) // > until month granularity
    let _ = dateC.isInRange(date: dateA, and: dateB, orEqual: true, granularity: .day) // > until day granularity
    let _ = dateA.earlierDate(dateB) // earlier date
    let _ = dateA.laterDate(dateB) // later date
    
    // Check if date is close to another with a given precision
    let _ = dateA.compareCloseTo(dateB, precision: 1.hours.timeInterval
    
    // Compare for relevant events:
    // .isToday, .isYesterday, .isTomorrow, .isWeekend, isNextWeek
    // .isSameDay, .isMorning, .isWeekday ...
    let _ = date.compare(.isToday)
    let _ = date.compare(.isNight)
    let _ = date.compare(.isNextWeek)
    let _ = date.compare(.isThisMonth)
    let _ = date.compare(.startOfWeek)
    let _ = date.compare(.isNextYear)
    // ...and MORE THAN 30 OTHER COMPARISONS BUILT IN
    
    // Operation in arrays (oldestIn, newestIn, sortedByNewest, sortedByOldest...)
    let _ = DateInRegion.oldestIn(list: datesArray)
    let _ = DateInRegion.sortedByNewest(list: datesArray)
    

    4、使用Region(Timezone, Calendar & Locale)创建Date

    您可以从字符串,时间间隔或使用日期组件创建新日期。 SwiftDate提供了一系列功能来创建和推倒您的日期,甚至随机生成!

    // All dates includes timezone, calendar and locales!
    // Create from string
    let rome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
    let date1 = DateInRegion("2010-01-01 00:00:00", region: rome)!
    
    // Create date from intervals
    let _ = DateInRegion(seconds: 39940, region: rome)
    let _ = DateInRegion(milliseconds: 5000, region: rome)
    
    // Date from components
    let _ = DateInRegion(components: {
        $0.year = 2001
        $0.month = 9
        $0.day = 11
        $0.hour = 12
        $0.minute = 0
    }, region: rome)
    let _ = DateInRegion(year: 2001, month: 1, day: 5, hour: 23, minute: 30, second: 0, region: rome)
    
    // Random date generation with/without bounds
    let _ = DateInRegion.randomDate(region: rome)
    let _ = DateInRegion.randomDate(withinDaysBeforeToday: 5)
    let _ = DateInRegion.randomDates(count: 50, between: lowerLimitDate, and: upperLimitDate, region: rome)
    

    5、派生日期

    也可以从其他日期开始生成日期,SwiftDate包含一组广泛的构造函数。 使用dateAt()函数可以轻松创建20多个不同的派生日期。

    let _ = DateInRegion().dateAt(.endOfDay) // today at the end of the day
    // Over 20 different relevant dates including .startOfDay,
    // .endOfDay, .startOfWeek, .tomorrow, .nextWeekday, .nextMonth, .prevYear, .nearestMinute and many others!
    let _ = dateA.nextWeekday(.friday) // the next friday after dateA
    let _ = (date.dateAt(.startOfMonth) - 3.days)
    let _ = dateA.compare(.endOfWeek)
    
    // Enumerate dates in range by providing your own custom
    // increment expressed in date components
    let from = DateInRegion("2015-01-01 10:00:00", region: rome)!
    let to = DateInRegion("2015-01-02 03:00:00", region: rome)!
    let increment2 = DateComponents.create {
        $0.hour = 1
        $0.minute = 30
        $0.second = 10
    }
    // generate dates in range by incrementing +1h,30m,10s each new date
    let dates = DateInRegion.enumerateDates(from: fromDate2, to: toDate2, increment: increment2)
    
    // Altering time components
    let _ = dateA.dateBySet(hour: 10, min: 0, secs: 0)
    
    // Truncating a date
    let _ = dateA.dateTruncated(at: [.year,.month,.day]) // reset all time components keeping only date
    
    // Rounding a date
    let _ = dateA.dateRoundedAt(.toMins(10))
    let _ = dateA.dateRoundedAt(.toFloor30Mins)
    
    // Adding components
    let _ = dateA.dateByAdding(5,.year)
    
    // Date at the start/end of any time component
    let _ = dateA.dateAtEndOf(.year) // 31 of Dec at 23:59:59
    let _ = dateA.dateAtStartOf(.day) // at 00:00:00 of the same day
    let _ = dateA.dateAtStartOf(.month) // at 00:00:00 of the first day of the month
    

    6、组成提取

    您可以直接从日期中提取组件,它包括在日期区域中表示的确切值(正确时区和区域设置!)。

    // Create a date in a region, London but with the lcoale set to IT
    let london = Region(calendar: .gregorian, zone: .europeLondon, locale: .italian)
    let date = DateInRegion("2018-02-05 23:14:45", format: dateFormat, region: london)!
    
    // You can extract any of the all available time units.
    // VALUES ARE EXPRESSED IN THE REGION OF THE DATE (THE RIGHT TIMEZONE).
    // (you can still get the UTC/absolute value by getting the inner's absoluteDate).
    
    let _ = date.year // 2018
    let _ = date.month // 2
    let _ = date.monthNameDefault // 'Febbraio' as the locale is the to IT!
    let _ = date.firstDayOfWeek // 5
    let _ = date.weekdayNameShort // 'Lun' as locale is the to IT
    // ... all components are supported: .year, .month, .day, .hour, .minute, .second,
    // .monthName, .weekday, .nearestHour, .firstDayOfWeek. .quarter and so on...
    

    7、在时区/区域设置和日历之间切换

    您可以轻松地将任何日期转换为其他区域(或者其他日历、区域、时区设置)! 新日期包含表示为目标原因的所有值。

    // Conversion between timezones is easy using convertTo(region:) function
    let rNY = Region(calendar: Calendars.gregorian, zone: Zones.americaNewYork, locale: Locales.english)
    let rRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
    let dateInNY = "2017-01-01 00:00:00".toDate(region: rNY)
    let dateInRome = dateInNY?.convertTo(region: rRome)!
    print(dateInRome.toString()) // "dom gen 01 06:00:00 +0100 2017\n"
    
    // You can also convert single region's attributes
    let dateInIndia = dateInNY?.convertTo(timezone: Zones.indianChristmas, locale: Locales.nepaliIndia)
    print("\(dateInIndia!.toString())") // "आइत जनवरी ०१ १२:००:०० +0700 २०१७\n"
    

    8、Date格式(Date转String)

    日期格式很简单,您可以指定自己的格式,区域设置或使用任何提供的格式。

    // Date Formatting
    let london = Region(calendar: .gregorian, zone: .europeLondon, locale: .english)
    let date = ... // 2017-07-22T18:27:02+02:00 in london region
    let _ = date.toDotNET() // /Date(1500740822000+0200)/
    let _ = date.toISODate() // 2017-07-22T18:27:02+02:00
    let _ = date.toFormat("dd MMM yyyy 'at' HH:mm") // "22 July 2017 at 18:27"
    
    // You can also easily change locale when formatting a region
    let _ = date.toFormat("dd MMM", locale: .italian) // "22 Luglio"
    
    // Time Interval Formatting as Countdown
    let interval: TimeInterval = (2.hours.timeInterval) + (34.minutes.timeInterval) + (5.seconds.timeInterval)
    let _ = interval.toClock() // "2:34:05"
    
    // Time Interval Formatting by Components
    let _ = interval.toString {
        $0.maximumUnitCount = 4
        $0.allowedUnits = [.day, .hour, .minute]
        $0.collapsesLargestUnit = true
        $0.unitsStyle = .abbreviated
    } // "2h 34m"
    

    9、相对日期格式(完全可自定义!)

    相对格式化是SwiftDate中的全新内容;它支持120多种语言,有两种不同的风格(.default.twitter),9种特例(.long.longTime.longConvenient.short.shortTime.shortConvenient.narrow.tiny.quantify)而且它们全都可以根据您的需要进行定制。 可扩展格式允许您提供自己的转换和规则以覆盖默认行为。

    // Twitter Style
    let _ = (Date() - 3.minutes).toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.english) // "3m"
    let _ = (Date() - 6.minutes).toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.italian) // "6 min fa"
    
    // Default Style
    let _ = (now2 - 5.hours).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.english) // "5 hours ago"
    let y = (now2 - 40.minutes).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.italian) // "45 minuti fa"
    

    10、 Codable支持

    DateInRegionRegion都完全支持新的Swift的Codable协议。 这意味着您可以安全地编码/解码它们:

    // Encoding/Decoding a Region
    let region = Region(calendar: Calendars.gregorian, zone: Zones.europeOslo, locale: Locales.english)
    let encodedJSON = try JSONEncoder().encode(region)
    let decodedRegion = try JSONDecoder().decode(Region.self, from: encodedJSON)
    
    // Encoding/Decoding a DateInRegion
    let date = DateInRegion("2015-09-24T13:20:55", region: region)
    let encodedDate = try JSONEncoder().encode(date)
    let decodedDate = try JSONDecoder().decode(DateInRegion.self, from: encodedDate)
    

    11、时间段

    SwiftDate集成了高手Matthew York的DateTools模块,以支持时间段。
    请参阅文档的“时间段”部分。

    相关文章

      网友评论

          本文标题:SwiftDate使用笔记(翻译)

          本文链接:https://www.haomeiwen.com/subject/gmxrpftx.html