xref: /haiku/src/apps/haikudepot/util/LocaleUtils.cpp (revision bb83316a5811a550c4f850d07fa8e328e7ac0a94)
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 
9 #include <Catalog.h>
10 #include <Collator.h>
11 #include <DateFormat.h>
12 #include <DateTimeFormat.h>
13 #include <Locale.h>
14 #include <LocaleRoster.h>
15 #include <StringFormat.h>
16 
17 #include "Logger.h"
18 
19 
20 #undef B_TRANSLATION_CONTEXT
21 #define B_TRANSLATION_CONTEXT "LocaleUtils"
22 
23 
24 BCollator* LocaleUtils::sSharedCollator = NULL;
25 
26 
27 /*static*/ BCollator*
28 LocaleUtils::GetSharedCollator()
29 {
30 	if (sSharedCollator == NULL) {
31 		sSharedCollator = new BCollator();
32 		GetCollator(sSharedCollator);
33 	}
34 
35 	return sSharedCollator;
36 }
37 
38 
39 /*static*/ void
40 LocaleUtils::GetCollator(BCollator* collator)
41 {
42 	const BLocale* locale = BLocaleRoster::Default()->GetDefaultLocale();
43 
44 	if (locale->GetCollator(collator) != B_OK)
45 		HDFATAL("unable to get the locale's collator");
46 }
47 
48 
49 /*static*/ BString
50 LocaleUtils::TimestampToDateTimeString(uint64 millis)
51 {
52 	if (millis == 0)
53 		return "?";
54 
55 	BDateTimeFormat format;
56 	BString buffer;
57 	if (format.Format(buffer, millis / 1000, B_SHORT_DATE_FORMAT,
58 			B_SHORT_TIME_FORMAT) != B_OK)
59 		return "!";
60 
61 	return buffer;
62 }
63 
64 
65 /*static*/ BString
66 LocaleUtils::TimestampToDateString(uint64 millis)
67 {
68 	if (millis == 0)
69 		return "?";
70 
71 	BDateFormat format;
72 	BString buffer;
73 	if (format.Format(buffer, millis / 1000, B_SHORT_DATE_FORMAT)
74 			!= B_OK)
75 		return "!";
76 
77 	return buffer;
78 }
79 
80 
81 /*!	This is used in situations where the user is required to confirm that they
82 	are as old or older than some minimal age.  This is associated with agreeing
83 	to the user usage conditions.
84 */
85 
86 /*static*/ BString
87 LocaleUtils::CreateTranslatedIAmMinimumAgeSlug(int minimumAge)
88 {
89 	BString slug;
90 	static BStringFormat format(B_TRANSLATE("{0, plural,"
91  		"one{I am at least one year old}"
92 		"other{I am # years of age or older}}"));
93 	format.Format(slug, minimumAge);
94 	return slug;
95 }
96