Date.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. * Copyright (c) 2020, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringBuilder.h>
  7. #include <LibCore/DateTime.h>
  8. #include <LibJS/Heap/Heap.h>
  9. #include <LibJS/Runtime/Date.h>
  10. #include <LibJS/Runtime/GlobalObject.h>
  11. namespace JS {
  12. Date* Date::create(GlobalObject& global_object, Core::DateTime datetime, u16 milliseconds, bool is_invalid)
  13. {
  14. return global_object.heap().allocate<Date>(global_object, datetime, milliseconds, is_invalid, *global_object.date_prototype());
  15. }
  16. Date::Date(Core::DateTime datetime, u16 milliseconds, bool is_invalid, Object& prototype)
  17. : Object(prototype)
  18. , m_datetime(datetime)
  19. , m_milliseconds(milliseconds)
  20. , m_is_invalid(is_invalid)
  21. {
  22. }
  23. Date::~Date()
  24. {
  25. }
  26. tm Date::to_utc_tm() const
  27. {
  28. time_t timestamp = m_datetime.timestamp();
  29. struct tm tm;
  30. gmtime_r(&timestamp, &tm);
  31. return tm;
  32. }
  33. int Date::utc_date() const
  34. {
  35. return to_utc_tm().tm_mday;
  36. }
  37. int Date::utc_day() const
  38. {
  39. return to_utc_tm().tm_wday;
  40. }
  41. int Date::utc_full_year() const
  42. {
  43. return to_utc_tm().tm_year + 1900;
  44. }
  45. int Date::utc_hours() const
  46. {
  47. return to_utc_tm().tm_hour;
  48. }
  49. int Date::utc_minutes() const
  50. {
  51. return to_utc_tm().tm_min;
  52. }
  53. int Date::utc_month() const
  54. {
  55. return to_utc_tm().tm_mon;
  56. }
  57. int Date::utc_seconds() const
  58. {
  59. return to_utc_tm().tm_sec;
  60. }
  61. String Date::gmt_date_string() const
  62. {
  63. // Mon, 18 Dec 1995 17:28:35 GMT
  64. // FIXME: Note that we're totally cheating with the timezone part here..
  65. return datetime().to_string("%a, %e %b %Y %T GMT");
  66. }
  67. String Date::iso_date_string() const
  68. {
  69. auto tm = to_utc_tm();
  70. int year = tm.tm_year + 1900;
  71. int month = tm.tm_mon + 1;
  72. StringBuilder builder;
  73. if (year < 0)
  74. builder.appendff("-{:06}", -year);
  75. else if (year > 9999)
  76. builder.appendff("+{:06}", year);
  77. else
  78. builder.appendff("{:04}", year);
  79. builder.append('-');
  80. builder.appendff("{:02}", month);
  81. builder.append('-');
  82. builder.appendff("{:02}", tm.tm_mday);
  83. builder.append('T');
  84. builder.appendff("{:02}", tm.tm_hour);
  85. builder.append(':');
  86. builder.appendff("{:02}", tm.tm_min);
  87. builder.append(':');
  88. builder.appendff("{:02}", tm.tm_sec);
  89. builder.append('.');
  90. builder.appendff("{:03}", m_milliseconds);
  91. builder.append('Z');
  92. return builder.build();
  93. }
  94. }