Time Formatting Parsing in TypeScript

Time formatting and parsing in TypeScript is typically done using the built-in Date object or third-party libraries like date-fns or moment.js. For this example, we’ll use the native Date object and create some helper functions to mimic the Go behavior.

// Helper function to format dates
function formatDate(date: Date, format: string): string {
  const pad = (n: number) => n.toString().padStart(2, '0');
  const formats: { [key: string]: string } = {
    'YYYY': date.getFullYear().toString(),
    'MM': pad(date.getMonth() + 1),
    'DD': pad(date.getDate()),
    'HH': pad(date.getHours()),
    'mm': pad(date.getMinutes()),
    'ss': pad(date.getSeconds()),
    'SSS': date.getMilliseconds().toString().padStart(3, '0'),
    'Z': date.toISOString().slice(19, 25)
  };
  
  return format.replace(/YYYY|MM|DD|HH|mm|ss|SSS|Z/g, match => formats[match]);
}

// Helper function to parse dates
function parseDate(dateString: string, format: string): Date {
  const parts = dateString.match(/\d+/g) || [];
  const formatParts = format.match(/YYYY|MM|DD|HH|mm|ss/g) || [];
  const dateParts: { [key: string]: number } = {};

  formatParts.forEach((part, index) => {
    dateParts[part] = parseInt(parts[index]);
  });

  return new Date(
    dateParts['YYYY'] || 0,
    (dateParts['MM'] || 1) - 1,
    dateParts['DD'] || 1,
    dateParts['HH'] || 0,
    dateParts['mm'] || 0,
    dateParts['ss'] || 0
  );
}

function main() {
  const p = console.log;

  // Here's a basic example of formatting a time
  // according to ISO8601, which is similar to RFC3339
  const t = new Date();
  p(t.toISOString());

  // Time parsing uses the same layout values as format
  const t1 = new Date('2012-11-01T22:08:41+00:00');
  p(t1);

  // Custom formatting
  p(formatDate(t, 'HH:mm'));
  p(formatDate(t, 'ddd MMM DD HH:mm:ss YYYY'));
  p(formatDate(t, 'YYYY-MM-DDTHH:mm:ss.SSSZ'));

  const form = 'HH:mm';
  const t2 = parseDate('20:41', form);
  p(t2);

  // For purely numeric representations you can also
  // use standard string formatting with the extracted
  // components of the time value.
  p(formatDate(t, 'YYYY-MM-DDTHH:mm:ss-00:00'));

  // Parse will return an error on malformed input
  // explaining the parsing problem.
  try {
    parseDate('8:41PM', 'HH:mm:ss');
  } catch (e) {
    p(e);
  }
}

main();

This TypeScript code demonstrates time formatting and parsing, similar to the original example. Here are some key points:

  1. We use the built-in Date object for handling dates and times.
  2. Custom formatDate and parseDate functions are implemented to mimic Go’s behavior.
  3. The toISOString() method is used to format dates according to ISO8601, which is similar to RFC3339.
  4. Custom date formats are defined using placeholders like ‘YYYY’, ‘MM’, ‘DD’, etc.
  5. Error handling for parsing is done using try-catch blocks.

When you run this code, it will output formatted dates and times, as well as parsed date objects. Note that the exact output will depend on the current time when you run the script.

TypeScript doesn’t have built-in constants for date formats like Go’s time.RFC3339, so we use string templates instead. Also, the parsing function in this example is simplified and may not handle all edge cases that Go’s time.Parse function does.