[英]Can someone explain to me why time is working like this?
我在此上花了很长时间,但无法创建适用于我的c程序的公式。 (我有一个新的程序员)。
我必须将UTC时间转换为特定城市的时间。 除了这里,我的代码运行完美。 这给了我错误的答案。 我无法解决这个问题(我创建了一个公式,但对我来说没有意义)。
在我的程序中,时间输入为24小时制。 9AM = 900、12PM = 1200、12am = 0等。
如果要求我们将2359转换为Eucla时间(UTC +845),我的程序将输出804。正确答案是844。我想出了如何计算844,但我没有任何意义。
2359 + 845 = 3204 (adding the timezone offset 845 to the UTC time)
3204 - 60 = 3144 (minus 60 for some reason [I followed my time overflow formula]
3144 - 2400 = 2400 (minus 2400 because time cannot be more than 2359)
我的程序如何运作
首先加上UTC和偏移时间
calculatedTime = UTC + offset;
然后在那下
if (calculatedTime < 2359) {
calculatedTime = calculatedTime - 2400;
}
我还有另一个功能可以检查下方的溢出时间
if (((calculatedTime > 59) && (calculatedTime < 99)) || ((calculatedTime > 159) && (calculatedTime < 199))) {
// All the way to 2359
calculatedTime = calculatedTime - 60 + 100;
}
您需要将时间分为几小时和几分钟。 然后将时区偏移量分别添加到小时和分钟。 处理翻转。 最后,将小时和分钟重新组合成最终答案。
像这样:
int main(void)
{
// inputs
int time = 2359;
int zone = 845;
// separate hours and minutes
int timeHours = time / 100;
int timeMinutes = time % 100;
int zoneHours = zone / 100;
int zoneMinutes = zone % 100;
// add the hours and minutes
int hours = timeHours + zoneHours;
int minutes = timeMinutes + zoneMinutes;
// handle the rollover conditions
if (minutes > 60) {
minutes -= 60;
hours++;
}
if (hours > 24) {
hours -= 24;
}
// recombine the hours and minutes
int adjustedTime = hours * 100 + minutes;
printf("%d\n", adjustedTime);
}
请注意,此代码仅适用于具有正偏移量的时区。 您需要弄清楚如何使其在负时区工作。
OP的代码有各种一次性错误。
// if (((calculatedTime > 59) && (calculatedTime < 99)) ||
// ((calculatedTime > 159) && (calculatedTime < 199))) {
if (((calculatedTime > 59) && (calculatedTime < 100)) ||
((calculatedTime > 159) && (calculatedTime < 200))) {
// if (hours > 24) {
// hours -= 24;
// }
if (hours >= 24) {
hours -= 24;
}
也码具有使用类似的值更清晰60, 100
if (((calculatedTime >= 60) && (calculatedTime < 100)) ||
((calculatedTime >= 60*2) && (calculatedTime < 100*2))) {
然而,OP的方法失败了,因为负数。
要处理正负时间值,请将“ hhmm”时间分为几个小时和几分钟。 寻找“分钟”溢出的条件。 我建议使用2个辅助函数来拆分和合并结果。
#include <stdio.h>
#include <stdlib.h>
void hhmm_split(int hhmm, int *hour, int *min) {
*hour = hhmm / 100;
*min = hhmm % 100;
}
/* `min` may be outside the primary range of (-60 ... 60) */
int hhmm_combine(int hour, int min) {
hour += min / 60;
min %= 60;
if (hour < 0 && min > 0) {
min -= 60;
hour++;
} else if (hour > 0 && min < 0) {
min += 60;
hour--;
}
hour %= 24;
return hour * 100 + min;
}
测试码
void hhmm_add(int t1, int t2) {
int t1_hh, t1_mm, t2_hh, t2_mm;
hhmm_split(t1, &t1_hh, &t1_mm);
hhmm_split(t2, &t2_hh, &t2_mm);
int sum = hhmm_combine(t1_hh + t2_hh, t1_mm + t2_mm);
printf("t1:% 05d + t2:% 05d = sum:% 05d\n", t1, t2, sum);
}
int main(void) {
hhmm_add(2359, 845);
hhmm_add(2359, -845);
hhmm_add(-2359, 845);
hhmm_add(-2359, -845);
}
输出:
t1: 2359 + t2: 0845 = sum: 0844
t1: 2359 + t2:-0845 = sum: 1514
t1:-2359 + t2: 0845 = sum:-1514
t1:-2359 + t2:-0845 = sum:-0844
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.