summaryrefslogtreecommitdiff
path: root/libicui18n/tests/basic/driver.cpp
blob: 40f36addad570d3fab8036a570367ae356367e26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// file      : tests/basic/driver.cpp
// license   : Unicode License; see accompanying LICENSE file

#include <string>
#include <memory>    // unique_ptr
#include <cassert>
#include <iostream>
#include <stdexcept> // runtime_error

#include <unicode/utypes.h>
#include <unicode/uclean.h>

#include <unicode/datefmt.h>
#include <unicode/calendar.h>
#include <unicode/timezone.h>
#include <unicode/bytestream.h>

// Usage: argv[0] <locale>
//
// Print the full 01/01/2020 00:00 time in Berlin's timezone using the
// specified locale.
//
int
main (int argc, char* argv[])
{
  using namespace std;
  using namespace icu;

  assert (argc == 2);
  const char* locale (argv[1]);

  UErrorCode e (U_ZERO_ERROR);

  auto validate = [&e] (const char* what)
  {
    if (U_FAILURE (e))
      throw runtime_error (string (what) + " failed: " + u_errorName (e));
  };

  int r (0);

  try
  {
    unique_ptr<Calendar> cal (Calendar::createInstance (e));
    validate ("Calendar::createInstance()");

    cal->adoptTimeZone (TimeZone::createTimeZone ("Europe/Berlin"));
    cal->clear ();
    cal->set (2020, Calendar::JANUARY, 1);

    UDate date (cal->getTime (e));
    validate ("Calendar::getTime()");

    unique_ptr<DateFormat> fmt (
      DateFormat::createDateTimeInstance (DateFormat::kFull,
                                          DateFormat::kFull,
                                          locale));

    fmt->setCalendar (*cal);

    UnicodeString us;
    fmt->format(date, us, e);
    validate ("DateFormat::format()");

    string s;
    StringByteSink<string> bs (&s);
    us.toUTF8 (bs);

    cout << s << endl;
  }
  catch (const runtime_error& e)
  {
    cerr << e.what () << endl;

    r = 1;
  }

  // Free any heap storage that has been potentially allocated and held by the
  // ICU library.
  //
  u_cleanup ();

  return r;
}