Reputation: 51
I'm trying to convert time from UTC time/date to what time it would be in Christchurch New Zealand. PS, I am a beginner coder.
I can easily identify the timezone offset and take into consideration daylight savings. My question is, how can I add UTC and the offset time (+1200)
int timeConverted (int utcTime, int timezoneOffset) {
int answer = 0;
int totalTime = utctime + timezoneOffset;
int timeAdded = totalTime;
if (timeAdded > 2359) {
answer = timeAdded - 2400;
}
return answer;
When I do this I get some funny looking answers. This is for Adelaide, Australia time
Input is 1659 Out is 189 (the answer should be 229)
I can only use if statements (no arrays or anything like that)
Upvotes: 1
Views: 77
Reputation: 84561
If I understand your question, and you want to take the UTC time and timezone offset and then compute local time (for Adelaide, Australia with +930
timezone offset), then you have 3 cases to handle:
59
? (if so add 40
)2359
? (if so subtract 2400
)0
(if so add 2400
)You can handle that in a fairly simple manner:
int timeConverted (int utcTime, int timezoneOffset) {
int answer = utcTime + timezoneOffset,
utcmin = utcTime % 100, /* consider minutes */
offmin = timezoneOffset % 100; /* from each time */
if (utcmin + offmin > 59) /* handle minutes 60-99 */
answer += 40;
if (answer > 2359) /* answer greater than 2359 */
answer -= 2400;
if (answer < 0) /* answer less than 0 */
answer += 2400;
return answer;
}
Putting it altogether in a simple example that takes utcTime
as the first argument to the program (1659
default) and takes timezoneOffset
as the second argument (1200
default), you could do something like the following:
#include <stdio.h>
#include <stdlib.h>
int timeConverted (int utcTime, int timezoneOffset) {
int answer = utcTime + timezoneOffset,
utcmin = utcTime % 100, /* consider minutes */
offmin = timezoneOffset % 100; /* from each time */
if (utcmin + offmin > 59) /* handle minutes 60-99 */
answer += 40;
if (answer > 2359) /* answer greater than 2359 */
answer -= 2400;
if (answer < 0) /* answer less than 0 */
answer += 2400;
return answer;
}
int main (int argc, char **argv) {
int utc = argc > 1 ? strtol (argv[1], NULL, 0) : 1659,
tzo = argc > 2 ? strtol (argv[2], NULL, 0) : 1200;
printf ("utcTime : %d\noffset : %d\nlocal : %d\n",
utc, tzo, timeConverted (utc, tzo));
}
(note: to set timezoneOffset
both arguments are required)
Example Use/Output
$ ./bin/tzoffset 1659 930
utcTime : 1659
offset : 930
local : 229
Look things over and let me know if you have further questions. (also let me know if I misunderstood your question)
Yes, now 2359 845
works correctly, e.g.
Example Use/Output
$ ./bin/tzoffset 2359 845
utcTime : 2359
offset : 845
local : 844
Upvotes: 1