2018-05-14 19:48:57 +02:00
/ * *
* @ author n1474335 [ n1474335 @ gmail . com ]
* @ copyright Crown Copyright 2016
* @ license Apache - 2.0
* /
2019-07-09 13:23:59 +02:00
import Operation from "../Operation.mjs" ;
2018-05-14 19:48:57 +02:00
import moment from "moment-timezone" ;
2019-07-09 13:23:59 +02:00
import { DATETIME _FORMATS , FORMAT _EXAMPLES } from "../lib/DateTime.mjs" ;
2018-05-14 19:48:57 +02:00
/ * *
* Translate DateTime Format operation
* /
class TranslateDateTimeFormat extends Operation {
/ * *
* TranslateDateTimeFormat constructor
* /
constructor ( ) {
super ( ) ;
this . name = "Translate DateTime Format" ;
this . module = "Default" ;
this . description = "Parses a datetime string in one format and re-writes it in another.<br><br>Run with no input to see the relevant format string examples." ;
2018-08-21 20:07:13 +02:00
this . infoURL = "https://momentjs.com/docs/#/parsing/string-format/" ;
2018-05-14 19:48:57 +02:00
this . inputType = "string" ;
2023-03-08 18:44:51 +01:00
this . outputType = "html" ;
2018-05-14 19:48:57 +02:00
this . args = [
{
"name" : "Built in formats" ,
"type" : "populateOption" ,
"value" : DATETIME _FORMATS ,
"target" : 1
} ,
{
"name" : "Input format string" ,
"type" : "binaryString" ,
"value" : "DD/MM/YYYY HH:mm:ss"
} ,
{
"name" : "Input timezone" ,
"type" : "option" ,
"value" : [ "UTC" ] . concat ( moment . tz . names ( ) )
} ,
{
"name" : "Output format string" ,
"type" : "binaryString" ,
"value" : "dddd Do MMMM YYYY HH:mm:ss Z z"
} ,
{
"name" : "Output timezone" ,
"type" : "option" ,
"value" : [ "UTC" ] . concat ( moment . tz . names ( ) )
}
] ;
}
/ * *
* @ param { string } input
* @ param { Object [ ] } args
2023-03-08 18:44:51 +01:00
* @ returns { html }
2018-05-14 19:48:57 +02:00
* /
run ( input , args ) {
2018-08-16 18:19:23 +02:00
const [ inputFormat , inputTimezone , outputFormat , outputTimezone ] = args . slice ( 1 ) ;
2018-05-14 19:48:57 +02:00
let date ;
try {
date = moment . tz ( input , inputFormat , inputTimezone ) ;
if ( ! date || date . format ( ) === "Invalid date" ) throw Error ;
} catch ( err ) {
2018-07-15 14:25:44 +02:00
return ` Invalid format. \n \n ${ FORMAT _EXAMPLES } ` ;
2018-05-14 19:48:57 +02:00
}
2023-03-08 18:44:51 +01:00
return date . tz ( outputTimezone ) . format ( outputFormat . replace ( /[<>]/g , "" ) ) ;
2018-05-14 19:48:57 +02:00
}
}
export default TranslateDateTimeFormat ;