I have 2 variables
MTIME="Jan_2_2012_23:55:49"
SCH_TIME="Jan_03_2012_00:32:28"
I want to find the time taken (in seconds) between MTIME and SCH_TIME.
Is there any way by which this can be done in Unix Shell Script?
I have 2 variables
MTIME="Jan_2_2012_23:55:49"
SCH_TIME="Jan_03_2012_00:32:28"
I want to find the time taken (in seconds) between MTIME and SCH_TIME.
Is there any way by which this can be done in Unix Shell Script?
If your date supports -d option, try this...
#!/bin/bash
MTIME="Jan_2_2012_23:55:49"
SCH_TIME="Jan_03_2012_00:32:28"
((DIFF=$(date -d "${SCH_TIME//_/ }" +%s ) - $(date -d "${MTIME//_/ }" +%s )))
echo "$DIFF Seconds"
--ahamed
Thank you Ahamed.
But this works only in Linux.
Is there a way of using it in Solaris (ksh)
A perl:
#!/usr/bin/perl
use strict;
use Time::Piece;
use POSIX qw(strftime);
# Time::Piece to create two time objects using the timestamps
my $MTIME="Jan_2_2012_23:55:49";
my $SCH_TIME="Jan_03_2012_00:32:28";
my $before = Time::Piece->strptime($MTIME , "%b_%d_%Y_%H:%M:%S");
my $after = Time::Piece->strptime($SCH_TIME, "%b_%d_%Y_%H:%M:%S");
# Gap in seconds
my $secdiff = int ($after - $before);
print "Seconds:$secdiff\n";
# Format the result .
print strftime( '%H:%M:%S', gmtime($secdiff))."\n";
A solution in nawk
nawk 'BEGIN{
MTIME="Jan_2_2012_23:55:49"; SCH_TIME="Jan_03_2012_00:32:28"
month="JanFebMarAprMayJunJulAugSepOctNovDec"
split(MTIME,a,"[_:]"); split(SCH_TIME,b,"[_:]")
t1=mktime(a[3]" "int((index(month,a[1])/3))+1" "a[2]" "a[4]" "a[5]" "a[6])
t2=mktime(b[3]" "int((index(month,b[1])/3))+1" "b[2]" "b[4]" "b[5]" "b[6])
print t2-t1" Seconds"
}'
--ahamed