1

I am trying to do the equivalent of NSDate() but with out importing Foundation.

Does the Darwin module have a way to do this?

I was looking at this answer but no dice How can I get a precise time, for example in milliseconds in Objective-C?

Community
  • 1
  • 1
Chéyo
  • 9,107
  • 9
  • 27
  • 44

1 Answers1

3

I am not sure if this is what you are looking for, but the BSD library function

let t = time(nil)

gives the number of seconds since the Unix epoch as an integer, so this is almost the same as

let t = NSDate().timeIntervalSince1970

only that the latter returns the time as a Double with higher precision. If you need this higher precision then you could use gettimeofday():

var tv = timeval()
gettimeofday(&tv, nil)
let t = Double(tv.tv_sec) + Double(tv.tv_usec) / Double(USEC_PER_SEC)

If you are looking for the time broken down to years, month, days, hours etc according to your local time zone, then use

var t = time(nil)
var tmValue = tm()
localtime_r(&t, &tmValue)
let year = tmValue.tm_year + 1900
let month = tmValue.tm_mon + 1
let day = tmValue.tm_mday
let hour = tmValue.tm_hour
// ...

tmValue is a struct tm, and the fields are described in https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/localtime.3.html.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • This is what I am thinking but in swift reaching into c http://stackoverflow.com/questions/1442116/how-to-get-date-and-time-value-in-c-program – Chéyo Sep 16 '15 at 21:35