1 /* 2 * Copyright 2019, Andrew Lindesay <apl@lindesay.co.nz>. 3 * All rights reserved. Distributed under the terms of the MIT License. 4 */ 5 #include "LocaleUtils.h" 6 7 #include <stdlib.h> 8 #include <unicode/datefmt.h> 9 #include <unicode/dtptngen.h> 10 #include <unicode/smpdtfmt.h> 11 12 #include <Collator.h> 13 #include <ICUWrapper.h> 14 #include <Locale.h> 15 #include <LocaleRoster.h> 16 17 18 BCollator* LocaleUtils::sSharedCollator = NULL; 19 20 21 /*static*/ BCollator* 22 LocaleUtils::GetSharedCollator() 23 { 24 if (sSharedCollator == NULL) { 25 sSharedCollator = new BCollator(); 26 GetCollator(sSharedCollator); 27 } 28 29 return sSharedCollator; 30 } 31 32 33 /*static*/ void 34 LocaleUtils::GetCollator(BCollator* collator) 35 { 36 const BLocale* locale = BLocaleRoster::Default()->GetDefaultLocale(); 37 38 if (B_OK != locale->GetCollator(collator)) { 39 debugger("unable to get the locale's collator"); 40 exit(EXIT_FAILURE); 41 } 42 } 43 44 45 /*! There was some difficulty in getting BDateTime and friends to 46 work for the purposes of this application. Data comes in as millis since 47 the epoc relative to GMT0. These need to be displayed in the local time 48 zone, but the timezone aspect never seems to be quite right with BDateTime! 49 For now, to avoid this work over-spilling into a debug of the date-time 50 classes in Haiku, I am adding this method that uses ICU directly in order 51 to get something basic working for now. Later this should be migrated to 52 use the BDateTime etc... classes from Haiku once these problems have been 53 ironed out. 54 */ 55 56 /*static*/ BString 57 LocaleUtils::TimestampToDateTimeString(uint64 millis) 58 { 59 if (millis == 0) 60 return "?"; 61 62 UnicodeString pattern("yyyy-MM-dd HH:mm:ss"); 63 // later use variants of DateFormat::createInstance() 64 UErrorCode success = U_ZERO_ERROR; 65 SimpleDateFormat sdf(pattern, success); 66 67 if (U_FAILURE(success)) 68 return "!"; 69 70 UnicodeString icuResult; 71 sdf.format((UDate) millis, icuResult); 72 BString result; 73 BStringByteSink converter(&result); 74 icuResult.toUTF8(converter); 75 return result; 76 } 77