Set 12 hour format in DS1302 RTC library

Hello Experts,

I need to set 12 hour format timing in DS1302 RTC HW and using DS1302 arduino library.
Seems, DS1302 RTC chip does support 24 and 12 hour format.
Can you please help me on this ?

C:\Users\Titus\Documents\Arduino\libraries\arduino-ds1302-master\DS1302.cpp

// Returns the hour in 24-hour format from the hour register value.
uint8_t hourFromRegisterValue(const uint8_t value) {
  uint8_t adj;
  if (value & 128)  // 12-hour mode
    adj = 12 * ((value & 32) >> 5);
  else           // 24-hour mode
    adj = 10 * ((value & (32 + 16)) >> 4);
  return (value & 15) + adj;
}

I am also okay with only 12hour format support by hardcod 12hr in the above code.

Regards,
Titus S.

I would simply not bother to change something about the library. Simply subtract 12 if hour is > 12. And set a PM flag if hour >= 12 && hour != 0.

uint8_t hour12 = hour()%12 == 0? 12 : hour()%12;

Although it's a lot quicker without the modulo :smiley: But neat one line solution :slight_smile:

septillion, BulldogLowell,

Wow, thanks for the solution.
It worked!
Thanks a lot.

septillion:
I would simply not bother to change something about the library. Simply subtract 12 if hour is > 12. And set a PM flag if hour >= 12 && hour != 0.

Well, almost. You cannot just subtract 12 when > 12. It misses the case of when 00:00 to 00:59 in 24 hour time is 12:00 to 12:59am in 12 hour time.

BulldogLowell:
uint8_t hour12 = hour()%12 == 0? 12 : hour()%12;

Very nice one liner.

One might be tempted to "improve" the test of "hour()%12==0" changing it to !hour()%12 - but that will fail since the test "if==0" catches two cases, 1) where time = 0 and 2) where time = 12.

Elegance in simplicity!

The only thing missing is what the OP hasn't realized as yet - that he needs the inverse back to 24 hour mode to SET the clock. When he wakes up on that count, he should just download the Arduino Time library which supports the conversion bi-directionally.

avr_fred:
Well, almost. You cannot just subtract 12 when > 12. It misses the case of when 00:00 to 00:59 in 24 hour time is 12:00 to 12:59am in 12 hour time.

You’re right :slight_smile: I’m a 24h guy myself. And I still think the 12h is weird… Not because of the two blocks of 12 (because even when you use 24h notation you call 20:00 eight o’clock) but because am/pm don’t align with the two 12h blocks :stuck_out_tongue:

avr_fred:
One might be tempted to “improve” the test of “hour()%12==0” changing it to !hour()%12 - but that will fail since the test “if==0” catches two cases, 1) where time = 0 and 2) where time = 12.

!(hour()%12) :slight_smile:

or slim it down:
hour()%12 ? hour()%12 : 12; :stuck_out_tongue:

septillion:
!(hour()%12) :slight_smile:

Duoh! Slaps head.