| /******************************************************************************** |
| * Copyright (c) 2020 Contributors to the Eclipse Foundation |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0 |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ********************************************************************************/ |
| |
| import * as moment from "moment"; |
| import {MomentFormatSpecification, MomentInput} from "moment"; |
| |
| export const momentFormatInternal = "YYYY-MM-DD"; |
| |
| export const momentFormatDisplayNumeric = "DD.MM.YYYY"; |
| |
| export const momentFormatDisplayFullDateAndTime = "DD.MM.YYYY HH:mm:ss"; |
| |
| /** |
| * Transforms a time string (or other MomentInputs) to a JS date object. |
| * @param input Time string (or other MomentInput) to parse. |
| * @param inputFormat Time format for the input. |
| * @param defaultDate Default date (if input is no valid date). |
| */ |
| export function parseMomentToDate(input: MomentInput, inputFormat: MomentFormatSpecification, defaultDate?: Date): Date { |
| try { |
| const m = moment(input, inputFormat); |
| return m.isValid() ? m.toDate() : defaultDate; |
| } catch (e) { |
| return defaultDate; |
| } |
| } |
| |
| /** |
| * Parses a time string from one format to another. |
| * @param input Time string which is parsed |
| * @param inputFormat Time format for the input |
| * @param outputFormat Time format for the result |
| */ |
| export function parseMomentToString( |
| input: MomentInput, |
| inputFormat: MomentFormatSpecification, |
| outputFormat: string |
| ): string { |
| try { |
| const m = moment(input, inputFormat); |
| return m.isValid() ? m.format(outputFormat) : ""; |
| } catch (e) { |
| return ""; |
| } |
| } |
| |
| /** |
| * Returns the time between two time strings in milliseconds. |
| */ |
| export function momentDiff(inputA: MomentInput, inputB: MomentInput, inputFormat: MomentFormatSpecification = momentFormatInternal) { |
| try { |
| const momentA = moment(inputA, inputFormat); |
| const momentB = moment(inputB, inputFormat); |
| return momentA.diff(momentB); |
| } finally { |
| // Do nothing... |
| } |
| } |