Ad Widget

Collapse

Date and time conversions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • markfree
    Senior Member
    • Apr 2019
    • 868

    #1

    Date and time conversions

    Whenever I get a timestamp value like "yyyymmddhhMMss", if necessary, I convert it to "unixtime" with a JavaScript preprocessing step.

    This script is usually sufficient:

    Code:
    // checks if the input value is null
    if (isNaN(Date.parse(value))) { return 0; }
    
    // break the timestamp string into date and time values
    var year = parseInt(value.substring(0, 4), 10);
    var month = parseInt(value.substring(4, 6), 10) - 1;
    var day = parseInt(value.substring(6, 8), 10);
    var hour = parseInt(value.substring(8, 10), 10);
    var minute = parseInt(value.substring(10, 12), 10);
    var second = parseInt(value.substring(12, 14), 10);
    
    // creates a new date and time object and converts it to unixtime
    var dateTime = new Date(year, month, day, hour, minute, second);
    var unixtime = dateTime.getTime() / 1000;
    return unixtime;
    I was wondering if anyone has a better way to do this kind of conversion?.
  • eric_at_2037
    Junior Member
    • May 2008
    • 12

    #2
    Hello,

    Have you try fmttime macro function?

    Other way, more reliable (works fine with ISO 8601 and ISO_8601 with timezone):

    Code:
    // checks if the input value is null
    if (isNaN(Date.parse(value))) { return 0; }
    
    // JavaScript Date function
    var timestamp = new Date(value).getTime()
    return timestamp;
    Last edited by eric_at_2037; 07-10-2024, 10:34.

    Comment

    • markfree
      Senior Member
      • Apr 2019
      • 868

      #3
      Hey, thanks. I appreciate your feedback.
      In my previous example, the input value is a string, and it's not a macro, so I can't use the "fmttime" function.

      The "Date()" function accepts strings as input, but only in date-time string format. It usually requires the ECMAScript format as input and support for other formats is not guaranteed. Implementations are allowed to support other date formats, but I believe the Ducktape implementation used on Zabbix does not support the string I suggested earlier.

      Therefore, using your suggested script results in an error.
      Click image for larger version  Name:	Screenshot from 2024-10-10 18-21-21.png Views:	0 Size:	15.8 KB ID:	492607
      Last edited by markfree; 11-10-2024, 02:20.

      Comment

      Working...