Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Toybox.Time;
- import Toybox.Lang;
- import Toybox.System;
- // Parse a number from a substring
- //
- // Throws an exception if startIndex/endIndex are out of bounds, or if the substring
- // can't be converted to a number
- function parseNumber(str as String, startIndex as Number, endIndex as Number) as Number {
- var num = str.substring(startIndex, endIndex);
- if (num == null) {
- throw new Exception();
- }
- num = num.toNumber();
- if (num == null) {
- throw new Exception();
- }
- return num;
- }
- function parseISO8601(timestamp as String) as Time.Moment? {
- // Accepts 2 formats:
- //
- // "2025-05-15T15:16:54Z"
- // "2025-05-15T15:16:54.123Z"
- //
- // milliseconds are ignored
- var length = timestamp.length();
- if (length != 20 && length != 24) {
- return null;
- }
- if (
- !("-").equals(timestamp.substring(4, 5)) ||
- !("-").equals(timestamp.substring(7, 8)) ||
- !("T").equals(timestamp.substring(10, 11)) ||
- !(":").equals(timestamp.substring(13, 14)) ||
- !(":").equals(timestamp.substring(16, 17)) ||
- !("Z").equals(timestamp.substring(length-1, length))
- ) {
- return null;
- }
- try {
- var options = {
- :year => parseNumber(timestamp, 0, 4),
- :month => parseNumber(timestamp, 5, 7),
- :day => parseNumber(timestamp, 8, 10),
- :hour => parseNumber(timestamp, 11, 13),
- :minute => parseNumber(timestamp, 14, 16),
- :second => parseNumber(timestamp, 17, 19),
- };
- return Gregorian.moment(options);
- } catch (e) {
- return null;
- }
- }
- function momentToLocalTime(moment as Time.Moment?) as String {
- if (moment == null) {
- return "--";
- }
- // Returns local date/time in 24h format.
- // TODO: Add your own code to handle 12h format if necessary
- var info = Gregorian.info(moment, Time.FORMAT_MEDIUM);
- // e.g. "Thu May 15 2025 11:16:54"
- return info.day_of_week + " " + info.month + " " + info.day + " " + info.year + " " + info.hour + ":" + info.min + ":" + info.sec;
- }
- function test() as Void {
- var timestamp = "2025-05-15T15:16:54Z";
- var moment = parseISO8601(timestamp);
- var localTime = momentToLocalTime(moment);
- System.println(localTime); // "Thu May 15 2025 11:16:54"
- timestamp = "2025-05-15T15:16:54.123Z";
- moment = parseISO8601(timestamp);
- localTime = momentToLocalTime(moment);
- System.println(localTime); // "Thu May 15 2025 11:16:54"
- timestamp = "ABCD-05-15T15:16:54Z"; // bad timestamp
- moment = parseISO8601(timestamp);
- localTime = momentToLocalTime(moment);
- System.println(localTime); // "--"
- timestamp = "bad timestamp";
- moment = parseISO8601(timestamp);
- localTime = momentToLocalTime(moment);
- System.println(localTime); // "--"
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement