FromUNIXTimestamp.mjs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. import OperationError from "../errors/OperationError";
  10. /**
  11. * From UNIX Timestamp operation
  12. */
  13. class FromUNIXTimestamp extends Operation {
  14. /**
  15. * FromUNIXTimestamp constructor
  16. */
  17. constructor() {
  18. super();
  19. this.name = "From UNIX Timestamp";
  20. this.module = "Default";
  21. this.description = "Converts a UNIX timestamp to a datetime string.<br><br>e.g. <code>978346800</code> becomes <code>Mon 1 January 2001 11:00:00 UTC</code><br><br>A UNIX timestamp is a 32-bit value representing the number of seconds since January 1, 1970 UTC (the UNIX epoch).";
  22. this.infoURL = "https://wikipedia.org/wiki/Unix_time";
  23. this.inputType = "number";
  24. this.outputType = "string";
  25. this.args = [
  26. {
  27. "name": "Units",
  28. "type": "option",
  29. "value": UNITS
  30. }
  31. ];
  32. this.patterns = [
  33. {
  34. match: "^1?\\d{9}$",
  35. flags: "",
  36. args: ["Seconds (s)"]
  37. },
  38. {
  39. match: "^1?\\d{12}$",
  40. flags: "",
  41. args: ["Milliseconds (ms)"]
  42. },
  43. {
  44. match: "^1?\\d{15}$",
  45. flags: "",
  46. args: ["Microseconds (μs)"]
  47. },
  48. {
  49. match: "^1?\\d{18}$",
  50. flags: "",
  51. args: ["Nanoseconds (ns)"]
  52. },
  53. ];
  54. }
  55. /**
  56. * @param {number} input
  57. * @param {Object[]} args
  58. * @returns {string}
  59. *
  60. * @throws {OperationError} if invalid unit
  61. */
  62. run(input, args) {
  63. const units = args[0];
  64. let d;
  65. input = parseFloat(input);
  66. if (units === "Seconds (s)") {
  67. d = moment.unix(input);
  68. return d.tz("UTC").format("ddd D MMMM YYYY HH:mm:ss") + " UTC";
  69. } else if (units === "Milliseconds (ms)") {
  70. d = moment(input);
  71. return d.tz("UTC").format("ddd D MMMM YYYY HH:mm:ss.SSS") + " UTC";
  72. } else if (units === "Microseconds (μs)") {
  73. d = moment(input / 1000);
  74. return d.tz("UTC").format("ddd D MMMM YYYY HH:mm:ss.SSS") + " UTC";
  75. } else if (units === "Nanoseconds (ns)") {
  76. d = moment(input / 1000000);
  77. return d.tz("UTC").format("ddd D MMMM YYYY HH:mm:ss.SSS") + " UTC";
  78. } else {
  79. throw new OperationError("Unrecognised unit");
  80. }
  81. }
  82. }
  83. export default FromUNIXTimestamp;