قالب وردپرس درنا توس
Home / IOS Development / # 288: DateComponentsFormatter Basic 📆 – Little Bites of Cocoa

# 288: DateComponentsFormatter Basic 📆 – Little Bites of Cocoa



Issue

Topics

In Bite # 287, we built a small extension to Date to allow us to format relative data strings like "10 minutes ago" . We used a bunch of if declarations and built our last String . This was a great way to learn about working with DateComponents but it turns out that Foundation actually gives a class to do something similar and it is much more powerful.

Today we continue to look at the Foundation's date and time related functionality with DateComponentsFormatter . Let's go diving.

Like his cousin DateFormatter (Bite # 286), DateComponentsFormatter is about converting a TimeInterval or DateComponents ] to a nicely formatted, human readable string . (Note: It does not support parsing Strings yet. Conversions are a one-way journey for now.

We start with a new format :

  la [1
9659000] format
= DateComponentsFormatter ()

Then we will configure some options:

  format .   unitsStyle    =  . [19659016] full 
  formatting  format ]   allowedUnits    =    [.   minutes   .   second ] 

And finally, we will ask for a Strict which describes an example TimeInterval :

  Formatter .   Strict   (  from      543.0 )    // "9 minutes, 3 seconds" 

Like many Foundation types, DateComponentsFormatter is a super adaptable power plant. such as try some more options:

  format .   unitsStyle    =  .   abbreviated 
  format .   strict   from :    123.0 ) 

  // "2m 3s" 
  format .   unitsStyle    =  .   short 
  format .     (  from :    123.0 ) 

  // "2 min, 3 sec" 
  format . ] unitsStyle    =      spellOut 
  format    string   (  from :    123.0 ). 

  ] /   format .   includesApproximationPhrase    =    true 
  formats .   includesTimeRemainingPhrase    =    true 
  true 
 ] formatting .   unitsStyle    =  .   map 
  format set r .   strict   (  from :    123.0 ) 

  // "About 2min 3sec remaining" 

Tidy. Fun Facts: If you have ever seen a progress bar or "remaining" bar in iOS or macOS you have seen a DateComponentsFormatter in action.

We only allow .minutes and .seconds . Let's try to allow some different sets of devices [19659000]:

  la    formats    =    DateComponentsFormatter   () 

  formats  .   unitsStyle    unitsStyle   ] =  .   full 

  formatting .   allowedUnits    =    [.   minutes   .   nest ] 
  formatter .   string   (  from :    1234567.0 ) 

  // "20.576 minutes, 7 seconds" 
 ] Formatting .   allowedUnits    =    [.   day   .   time   .        second ] 
  formatting    string   (  from :    1234567.0  ). [19659056] // "14 days, 6 hours, 56 minutes, 7 seconds" 
  format .   allowedUnits    = [19659024] [.   day   .   minutes   .   Other ] 
  Formats .   strict   (  from :    1234567.0 ) 

  // "14 days, 416 minutes, 7 seconds" 

Tidy!

This is just very basic. Watch out for some more advanced DateComponentsFormatter fun soon.


Source link