Jeff Thompson | 9ae4d78 | 2013-10-17 10:25:54 -0700 | [diff] [blame] | 1 | /** |
| 2 | * Copyright (C) 2013 Regents of the University of California. |
| 3 | * @author: Jeff Thompson <jefft0@remap.ucla.edu> |
| 4 | * See COPYING for copyright and distribution information. |
| 5 | */ |
| 6 | |
| 7 | #include <sys/time.h> |
Jeff Thompson | 5a6ce83 | 2013-10-18 11:54:35 -0700 | [diff] [blame] | 8 | #include <math.h> |
| 9 | #include <string.h> |
| 10 | #include <stdio.h> |
Jeff Thompson | 9ae4d78 | 2013-10-17 10:25:54 -0700 | [diff] [blame] | 11 | #include "time.h" |
| 12 | |
Jeff Thompson | 9a8e82f | 2013-10-17 14:13:43 -0700 | [diff] [blame] | 13 | ndn_MillisecondsSince1970 |
Jeff Thompson | 9ae4d78 | 2013-10-17 10:25:54 -0700 | [diff] [blame] | 14 | ndn_getNowMilliseconds() |
| 15 | { |
| 16 | struct timeval t; |
| 17 | gettimeofday(&t, 0); |
| 18 | return t.tv_sec * 1000.0 + t.tv_usec / 1000.0; |
| 19 | } |
Jeff Thompson | 5a6ce83 | 2013-10-18 11:54:35 -0700 | [diff] [blame] | 20 | |
| 21 | void |
| 22 | ndn_toIsoString(ndn_MillisecondsSince1970 time, char *isoString) |
| 23 | { |
| 24 | double secondsSince1970 = time / 1000.0; |
| 25 | char fractionBuffer[10]; |
| 26 | sprintf(fractionBuffer, "%.06lf", fmod(secondsSince1970, 1.0)); |
| 27 | const char *fraction = strchr(fractionBuffer, '.'); |
| 28 | if (!fraction) |
| 29 | // Don't expect this to happen. |
| 30 | fraction = ".000000"; |
| 31 | |
| 32 | time_t seconds = secondsSince1970; |
| 33 | struct tm* gmt = gmtime(&seconds); |
| 34 | sprintf(isoString, "%04d%02d%02dT%02d%02d%02d%s", 1900 + gmt->tm_year, gmt->tm_mon + 1, gmt->tm_mday, |
| 35 | gmt->tm_hour, gmt->tm_min, gmt->tm_sec, fraction); |
| 36 | } |
Jeff Thompson | fdaaa58 | 2013-10-18 13:05:10 -0700 | [diff] [blame^] | 37 | |
| 38 | ndn_MillisecondsSince1970 |
| 39 | ndn_fromIsoString(const char* isoString) |
| 40 | { |
| 41 | // Initialize time zone, etc. |
| 42 | time_t dummyTime = 0; |
| 43 | struct tm time = *gmtime(&dummyTime); |
| 44 | |
| 45 | sscanf(isoString, "%4d%2d%2dT%2d%2d", &time.tm_year, &time.tm_mon, &time.tm_mday, &time.tm_hour, &time.tm_min); |
| 46 | // Skip the time past minutes and get the float seconds. |
| 47 | double seconds; |
| 48 | sscanf(isoString + (4 + 2 + 2 + 1 + 2 + 2), "%lf", &seconds); |
| 49 | |
| 50 | // tm_year starts from 1900. |
| 51 | time.tm_year -= 1900; |
| 52 | // tm_mon starts from 0, not 1. |
| 53 | time.tm_mon -= 1; |
| 54 | time.tm_sec = 0; |
| 55 | return (timegm(&time) + seconds) * 1000.0; |
| 56 | } |