title: Conversion of dates in swift without loss
body: <p><strong>Goal/Problem</strong></p>
  
  <p>I want to convert a <code>Date</code> into a <code>String</code> and back to a <code>Date</code>. I am able to do this but I am losing precision on the way. How can I make sure that not a single <em>bit</em> gets lost in the process?</p>
  
  <p><code>1573827905079978</code> vs <code>157382790508</code></p>
  
  <p><strong>Main code</strong></p>
  
  <pre><code>var now = Date()
  
  var now_as_string = Date.dateAsString(style: .dayMonthYearHourMinuteSecondMillisecondTimezone, date: now)
  var back_as_date =   Date.stringAsDate(style: .dayMonthYearHourMinuteSecondMillisecondTimezone, string: now_as_string)
  
  print(Date.dateAsTimeIntervalSince1970WithoutDots(date: now))
  print(Date.dateAsTimeIntervalSince1970WithoutDots(date: back_as_date))
  </code></pre>
  
  <p><strong>Output</strong></p>
  
  <p>1573827905079978</p>
  
  <p>157382790508</p>
  
  <p><strong>Date Extension (the place where the real magic happens)</strong></p>
  
  <pre><code>import Foundation
  
  extension Date {
  
      enum Style {
          case dayMonthYear
          case dayMonthYearHourMinute
          case dayMonthYearHourMinuteSecondMillisecondTimezone
      }
  
      static func dateAsString(style: Date.Style, date: Date) -&gt; String{
  
          let formatter = DateFormatter()
          formatter.dateFormat = fromStyleToString(style: style)
  
          return formatter.string(from: date)
  
      }
  
      private static func fromStyleToString(style: Date.Style) -&gt; String{
  
          switch style {
  
          case .dayMonthYear:
              return "dd.MM.yyyy"
  
          case .dayMonthYearHourMinute:
              return "dd.MM.yyyy HH:mm"
  
          case .dayMonthYearHourMinuteSecondMillisecondTimezone:
              return "dd.MM.yyyy HH:mm:ss:SSS Z"
  
          }
  
      }
  
      static func stringAsDate(style: Date.Style, string: String) -&gt; Date{
  
          let formatter = DateFormatter()
          formatter.dateFormat = fromStyleToString(style: style)
          return formatter.date(from: string)!
  
      }
  
      static func dateAsTimeIntervalSince1970WithoutDots(date: Date) -&gt; String{
          return String(date.timeIntervalSince1970).replacingOccurrences(of: ".", with: "")
      }
  
  }
  </code></pre>