55 lines
		
	
	
	
		
			1.4 KiB
		
	
	
	
		
			C
		
	
	
	
	
	
		
		
			
		
	
	
			55 lines
		
	
	
	
		
			1.4 KiB
		
	
	
	
		
			C
		
	
	
	
	
	
|  | #include <stdio.h>
 | ||
|  | #include <time.h>
 | ||
|  | 
 | ||
|  | #include <hexagram/clock.h>
 | ||
|  | 
 | ||
|  | static ssize_t format_text(hexagram_text *text, char *buf, size_t len) { | ||
|  |     hexagram_clock *clock = (hexagram_clock *)text; | ||
|  |     switch (clock->format) { | ||
|  |         case HEXAGRAM_CLOCK_24H: | ||
|  |             return snprintf(buf, len, "%d:%02d", | ||
|  |                             clock->time.hour, clock->time.minute); | ||
|  | 
 | ||
|  |         case HEXAGRAM_CLOCK_12H: | ||
|  |             return snprintf(buf, len, "%d:%02d %s", | ||
|  |                             clock->time.hour, clock->time.minute, | ||
|  |                             clock->time.hour < 12? "am": "pm"); | ||
|  |     } | ||
|  | 
 | ||
|  |     return 0; | ||
|  | } | ||
|  | 
 | ||
|  | int hexagram_clock_init(hexagram_clock *clock, | ||
|  |                         double x, | ||
|  |                         double y, | ||
|  |                         hexagram_text_align align, | ||
|  |                         hexagram_clock_format format) { | ||
|  |     if (hexagram_text_init(&clock->text, | ||
|  |                            x, | ||
|  |                            y, | ||
|  |                            align, | ||
|  |                            format_text) < 0) { | ||
|  |         goto error_text_init; | ||
|  |     } | ||
|  | 
 | ||
|  |     clock->format      = format; | ||
|  |     clock->time.hour   = 0; | ||
|  |     clock->time.minute = 0; | ||
|  | 
 | ||
|  |     return 0; | ||
|  | 
 | ||
|  | error_text_init: | ||
|  |     return -1; | ||
|  | } | ||
|  | 
 | ||
|  | void hexagram_clock_set(hexagram_clock *clock, time_t now) { | ||
|  |     struct tm *now_tm; | ||
|  | 
 | ||
|  |     if ((now_tm = localtime(&now)) == NULL) { | ||
|  |         return; | ||
|  |     } | ||
|  | 
 | ||
|  |     clock->time.hour   = now_tm->tm_hour; | ||
|  |     clock->time.minute = now_tm->tm_min; | ||
|  | } |