0

I have a server which collects information from several devices. Each device is in a different time zone then the server. I wish to compare the time of the server to the time the device sends the server. 1. How can the device get its current time including the time zone (this will be sent to the server)? 2. How can the server compare its local time to the time given from the server?

Shay
  • 633
  • 2
  • 11
  • 27

1 Answers1

0

You might use Boost date_time library which is fully prepared to deal with timezones. Your code might look similar to:

// The device will collect the time and send it to the server
// along its timezone information (e.g., US East Coast)
ptime curr_time(second_clock::local_time());

// The server will first convert that time to UTC using the timezone information.
// Alternatively, the server may just send UTC time.
typedef boost::date_time::local_adjustor<ptime, -5, us_dst> us_eastern;
ptime utc_time = us_eastern::local_to_utc(curr_time);

// Finally the server will convert UTC time to local time (e.g., US Arizona).
typedef boost::date_time::local_adjustor<ptime, -7, no_dst> us_arizona;
ptime local_time = us_arizona::utc_to_local(utc_time);
std::cout << to_simple_string(local_time) << std::endl;

In order to take care of DST you need to manually specify it during the local adjustor definition (us_eastern and us_arizona in the example code). DST support is included for US, but you can use the DST utilities for dealing with DST for other countries (you will need to define DST rules on a per-country basis, though).

betabandido
  • 18,946
  • 11
  • 62
  • 76
  • what is -5 in local_adjust? How do I know the rime zone of the machine? (its linux - the user can config it so i cant do it hard coded) When converting back from UTC to local time, how does boost know to what time zone to convert to? – Shay Jul 22 '12 at 18:01
  • You can't ignore daylight savings time. – Hans Passant Jul 22 '12 at 18:03
  • @Shay It seems there is not a portable way to get the timezone (see this [related question](http://stackoverflow.com/questions/3118582/how-do-i-find-the-current-system-timezone). The timezone could be configured during the installation process, for instance. – betabandido Jul 22 '12 at 18:42
  • @Shay I updated the answer to show a better handling for DST. As you can see it will not be 100% automatic, though (especially if you want to support timezones outside of US). – betabandido Jul 22 '12 at 18:49