ToUNIXTimestamp.mjs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * @author n1474335 [n1474335@gmail.com]
  3. * @copyright Crown Copyright 2016
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation";
  7. import moment from "moment-timezone";
  8. import {UNITS} from "../lib/DateTime";
  9. /**
  10. * To UNIX Timestamp operation
  11. */
  12. class ToUNIXTimestamp extends Operation {
  13. /**
  14. * ToUNIXTimestamp constructor
  15. */
  16. constructor() {
  17. super();
  18. this.name = "To UNIX Timestamp";
  19. this.module = "Default";
  20. this.description = "Parses a datetime string in UTC and returns the corresponding UNIX timestamp.<br><br>e.g. <code>Mon 1 January 2001 11:00:00</code> becomes <code>978346800</code><br><br>A UNIX timestamp is a 32-bit value representing the number of seconds since January 1, 1970 UTC (the UNIX epoch).";
  21. this.inputType = "string";
  22. this.outputType = "string";
  23. this.args = [
  24. {
  25. "name": "Units",
  26. "type": "option",
  27. "value": UNITS
  28. },
  29. {
  30. "name": "Treat as UTC",
  31. "type": "boolean",
  32. "value": true
  33. },
  34. {
  35. "name": "Show parsed datetime",
  36. "type": "boolean",
  37. "value": true
  38. }
  39. ];
  40. }
  41. /**
  42. * @param {string} input
  43. * @param {Object[]} args
  44. * @returns {string}
  45. */
  46. run(input, args) {
  47. const [units, treatAsUTC, showDateTime] = args,
  48. d = treatAsUTC ? moment.utc(input) : moment(input);
  49. let result = "";
  50. if (units === "Seconds (s)") {
  51. result = d.unix();
  52. } else if (units === "Milliseconds (ms)") {
  53. result = d.valueOf();
  54. } else if (units === "Microseconds (μs)") {
  55. result = d.valueOf() * 1000;
  56. } else if (units === "Nanoseconds (ns)") {
  57. result = d.valueOf() * 1000000;
  58. } else {
  59. throw "Unrecognised unit";
  60. }
  61. return showDateTime ? `${result} (${d.tz("UTC").format("ddd D MMMM YYYY HH:mm:ss")} UTC)` : result.toString();
  62. }
  63. }
  64. export default ToUNIXTimestamp;