Author's Name Its all about writing codes....

Time Difference in Lua

Feb 29, 2012 10:30 PM




In my post on Introduction to Lua Programming Language, I promised to always post some of my Lua codes, that may be useful. The code snippet below is meant to compute the time difference between a given time and the current system's time.


function GetTimeDifference(intialTime,finalTime)
	initialHour=tonumber(string.sub(intialTime,1,2)) *3600
	initialMinute=tonumber(string.sub(intialTime,4,5))*60
	initialSecond=tonumber(string.sub(intialTime,7,8))

	finalHour=tonumber(string.sub(finalTime,1,2))*3600
	finalMinute=tonumber(string.sub(finalTime,4,5))*60
	finalSecond=tonumber(string.sub(finalTime,7,8))

	totalInitialTime=initialHour+initialMinute+initialSecond
	totalFinalTime=finalHour+finalMinute+finalSecond
	local duration=totalFinalTime-totalInitialTime

	formatedDuration="00:00:00"
	if(duration<10) then
		formatedDuration="00:00:0"..duration
	elseif(duration>9 and duration<60) then
		formatedDuration="00:00:"..duration
	elseif(duration>59 and duration<=3600 ) then
		--minutes handler
		intermediateCalc=(duration/60)
		i,j=string.find(tostring(intermediateCalc),".")
		if(i==nil and j==nil) then
		  formatedDuration="00:0"..intermediateCalc
		else
		   min=string.sub(tostring(intermediateCalc),i,j)
		   if(tonumber(min)<10) then
			formatedDuration="00:0"..min
		   else
		  	formatedDuration="00:"..min
		  end
		end

		newSeconds=duration%60
		if(newSeconds<10) then
			formatedDuration=formatedDuration..":0"
        			..newSeconds
		else
			formatedDuration=formatedDuration..":"
     			..newSeconds
		end
	else
		--hour handler

		newMinutes=(finalMinute-initialMinute)/60
		if(newMinutes<0) then
		  newMinutes=newMinutes*-1
		end

		if(newMinutes<10) then
			newMinutes="0"..newMinutes
		end

		newSeconds=(finalSecond-initialSecond)
		if(newSeconds<0) then
		  newSeconds=newSeconds*-1
		end

		if(newSeconds<10) then
			newSeconds="0"..newSeconds
		end

		formatedDuration=(finalHour-initialHour)/3600
 		 ..":"..newMinutes..":"..newSeconds
	end
	return formatedDuration
end

	initialTime="10:30:45"
	finalTime=os.date("%H:%M:%S")
	print("")
	print ("The Initial Time is "..initialTime)
	print("")
	print ("The Current Time is "..finalTime)
	print("")
	duration=GetTimeDifference(initialTime,finalTime)
	print ("The Time Difference is "..duration)
	print("")

        

The program output is as seen below
 
                              time difference







Share this page on


0 Older Comment(s)   1 Like(s)   Permalink  

 Click  To Like This Page

comments powered by Disqus



Older Comment(s)

page