Tag Archive for time

Add st, nd, rd, th to days :D

function fday($time) {
	$day = date('d', $time);
	if ( substr($day, -1) == 1 ):
		$end = 'st';
	elseif ( substr($day, -1) == 2 ):
		$end = 'nd';
	elseif ( substr($day, -1) == 3 ):
		$end = 'rd';
	else:
		$end = 'th';
	endif;
	
	return date('F, d', $time).$end.date(' Y', $time);;
}

Usage:
$time = time();
echo fday($time);

source

Date and Time Difference calculates in PHP

/**
 * Calculates the differences between two date
 * 
 * @param date $date1
 * @param date $date2
 * @return array
 */
function dateDifference($date1, $date2)
{
    $d1 = (is_string($date1) ? strtotime($date1) : $date1);
    $d2 = (is_string($date2) ? strtotime($date2) : $date2);

    $diff_secs = abs($d1 - $d2);
    $base_year = min(date("Y", $d1), date("Y", $d2));

    $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);

    return array
    (
        "years"                 => abs(substr(date('Ymd', $d1) - date('Ymd', $d2), 0, -4)),
        "months_total"  => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
        "months"                => date("n", $diff) - 1,
        "days_total"    => floor($diff_secs / (3600 * 24)),
        "days"                  => date("j", $diff) - 1,
        "hours_total"   => floor($diff_secs / 3600),
        "hours"                 => date("G", $diff),
        "minutes_total" => floor($diff_secs / 60),
        "minutes"               => (int) date("i", $diff),
        "seconds_total" => $diff_secs,
        "seconds"               => (int) date("s", $diff)
    );
}

source

Basic usage of TNT library #1

#include <iostream>

/*
 Here we use the TNT library which contains headers for 1D,2D & 3D arrays supporting both C and FORTRAN 
 style arrays. The classes are templated allowing any array types. Moreover the classes support overloaded
 operators for common operations
*/
#include "tnt.h" //this is the only necessary header to use the entire library. However it is possible to only use the
 				 //needed headers depending on the desired functionality.

int main (int argc, char * const argv[]) {
	/* TNT::Stopwatch */
	TNT::Stopwatch timer1; //using TNT's 'Stopwatch' class to create a timer
	timer1.start();	//using the 'start' function of the timer to start counting time
	
	
	//use TNT's 'Array2D' class to create 3 30x30 arrays of which the first two are filled with the
	//value '2.0' while the 3rd is full of zeros
	TNT::Array2D<int> num(5,5,2.0); 
	TNT::Array2D<int> num2(5,5,2.0);
	TNT::Array2D<int> num3(5,5,0.0);
	
	std::cout<<num[0][0]<<"n"; //access a specific value in the matrix
	
	num3=num2*num; //element-wise multiplication of the two arrays using the overloaded '*' operator
	
	std::cout << num3 <<"n"; //using the overloaded operator '<<' to print the dimensions and contents of the array

	//using the 'matmult' function to multiply two matrices and then we print the result
	std::cout << TNT::matmult(num,num2) <<"n"; 
	
	std::cout<< num.subarray(1, 3, 1, 3); //using the 'subarray' function we print a part of the 'num' array
	
	/* TNT::Stopwatch */	
	//using the 'stop' function of the timer to stop counting. This function returns the time
	//elapsed from the call of the 'start' function in seconds.
	std::cout << timer1.stop()<<"n"; 
	
	
	
	
	return 0;
}

source

Timer.js

"use strict";

/*jslint white: true, browser: true, onevar: true, undef: true, eqeqeq: true, 
plusplus: true, bitwise: true, strict: true, newcap: true, immed: true, 
maxlen: 200 */

/*global window: true */

/** 
 * Timer.js
 * <a href="http://rolandog.com" >http://rolandog.com</a>
 *
 * License: Creative Commons Attribution-Share Alike 3.0 Unported.
 * <a href="http://creativecommons.org/licenses/by-sa/3.0/" >http://creativecommons.org/licenses/by-sa/3.0/</a>
 *
 * @projectDescription   Performs calculations on how much time has passed.
 * @author               Rolando Garza <a href="mailto:rolandog@gmail.com">rolandog@gmail.com</a>
 */

/**
 * A constructor that takes a date and returns a Timer object
 * with several calculations. You can enter a string, or number by number or 
 * even use it as a counter by calling it as new Timer().
 * @param(String) YYYY A String formatted like YYYY/MM/DD HH:MM:SS.ms
 */
var Timer = function Timer(YYYY, MM, DD, hh, mm, ss, ms) {
    //rounds a date: from 2009/08/21 14:42.123 you'll get 2009/08/21
    function round(d) {
        return new Date("" + d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate());
    }
    function properties(d) {
        return {
            Y: d.getFullYear(),
            M: d.getMonth(),
            D: d.getDate(),
            h: d.getHours(),
            m: d.getMinutes(),
            s: d.getSeconds(),
            ms: d.getMilliseconds(),
            t: d.getTime(),
            d: d
        };
    }
    this.exactly = {};
    this.rounded = {};
    //variable declarations
    var start, date, Counter, ww;
    //start is the moment the event started (from the date string)
    if (typeof(YYYY) === "string") {
        //in case there was a decimal place
        start = YYYY.split(".");
        ms = start[1] ? +("0." + start[1]) * 1000 : undefined;
        YYYY = start[0];
        start = new Date(YYYY);
        if (ms) {
            start.setMilliseconds(ms);
        }
    } else {
        //in case a variable is undefined
        MM = MM ? MM : "01";
        DD = DD ? DD : "01";
        hh = hh ? hh : "00";
        mm = mm ? mm : "00";
        ss = ss ? ss : "00";
        //firefox doesn't recognize 2009-6-6 but does recognize 2009/6/6. Weird.
        date = [YYYY, MM, DD].join("/") + " " + [hh, mm, ss].join(":");
        start = YYYY ? new Date(date) : new Date(); //starts a counter if YYYY is undefined
        if (ms) {
            start.setMilliseconds(ms);
        }
    }
    this.p = properties(start);
    //the infamous Counter class.
    Counter = function Counter(rounded, conversions) {
        function update() {
            var now, today, a, b, dt, pl = 100;
            now = new Date();
            today = round(now);
            a = now > start ? start : now;
            b = now > start ? now : start;
            a = properties(rounded ? round(a) : a);
            b = properties(rounded ? round(b) : b);
            dt = b.d - a.d;
            if (conversions) {
                if (rounded) {
                    pl = 1;
                }
                ms = parseInt(pl * dt, 10) / pl;
                ss = parseInt(pl * (dt /= 1000), 10) / pl;
                mm = parseInt(pl * (dt /= 60), 10) / pl;
                hh = parseInt(pl * (dt /= 60), 10) / pl;
                DD = parseInt(pl * (dt /= 24), 10) / pl;
                ww = parseInt(pl * DD / 7, 10) / pl;
                MM = parseInt(pl * (dt /= (365.25 / 12)), 10) / pl;
                YYYY = parseInt(pl * (dt /= 12), 10) / pl;
            } else {
                YYYY = b.Y - a.Y;
                MM = b.M - a.M;
                DD = b.D - a.D;
                hh = b.h - a.h;
                mm = b.m - a.m;
                ss = b.s - a.s;
                ms = b.ms - a.ms;
                if (ms < 0) {
                    ss -= 1;
                    ms += 1000;
                }
                if (ss < 0) {
                    mm -= 1;
                    ss += 60;
                }
                if (mm < 0) {
                    hh -= 1;
                    mm += 60;
                }
                if (hh < 0) {
                    DD -= 1;
                    hh += 24;
                }
                if (DD < 0) {
                    MM -= 1;
                    DD += 30;
                }
                if (MM < 0) {
                    YYYY -= 1;
                    MM += 12;
                }
                ww = (YYYY * 365.25 / 7) + (MM * 365.25 / 7 / 12) + (DD / 7);
                ww = parseInt(ww, 10);
            }
            return {
                years : YYYY,
                months : MM,
                days : DD,
                hours : hh,
                minutes : mm,
                seconds : ss,
                milliseconds : ms,
                weeks : ww
            };
        }
        this.__defineGetter__("years", function years() {
            return update().years;
        });
        this.__defineGetter__("months", function months() {
            return update().months;
        });
        this.__defineGetter__("days", function days() {
            return update().days;
        });
        this.__defineGetter__("hours", function hours() {
            return update().hours;
        });
        this.__defineGetter__("minutes", function minutes() {
            return update().minutes;
        });
        this.__defineGetter__("seconds", function seconds() {
            return update().seconds;
        });
        this.__defineGetter__("milliseconds", function milliseconds() {
            return update().milliseconds;
        });
        this.__defineGetter__("weeks", function weeks() {
            return update().weeks;
        });
        this.__defineGetter__("status", function status() {
            var i, r = [], u;
            u = "years months days weeks hours minutes seconds milliseconds".split(" ");
            for (i in u) {
                if (this.hasOwnProperty(u[i]) && this[u[i]]) {
                    if (u[i] === "weeks") {
                        r.push("(" + this[u[i]] + " " + u[i] + ")");
                    } else {
                        r.push(this[u[i]] + " " + u[i]);
                    }
                }
            }
            return r.join(",
");
        });
        this.fireworks = function fireworks() {
            var s = this.status;
            s = s.replace(/
/g, " ");
            s = s.replace(/ /g, "%20");
            s = s.replace(/,%20(.+/g, "");
            //Thanks Kenneth Kufluk
            //return "<a href="http://js-fireworks.appspot.com/?msg="" >http://js-fireworks.appspot.com/?msg="</a> + s; //for debugging
            window.location.href = "<a href="http://js-fireworks.appspot.com/?msg="" >http://js-fireworks.appspot.com/?msg="</a> + s;
        };
    };
    this.exactly.howMany = new Counter(0);
    this.exactly.conversions = new Counter(0, 1);
    this.rounded.howMany = new Counter(1);
    this.rounded.conversions = new Counter(1, 1);
};

/* Usage: 
 * Every Timer has three sub-objects: 'p', 'exactly' and 'rounded'
 * the 'p' object has the following properties:
 *     Y, M, D, h, m, s, ms, d, t
 * The last two are for the original date object and it's time-equivalent.
 * Y is short-hand for yourTimer.d.getFullYear(); the rest is self-explanatory.
 *
 * 'exactly' and 'rounded' are objects with the following properties:
 *     years, months, days, weeks, hours, minutes, seconds, milliseconds, status
 * 'status' displays a pre-formatted status message.
 */

/* Example with comments: 
 var asd, jkl, qwe, uio;
 asd = new Timer(); //starts counting from 'now'.
 jkl = new Timer("2010/2/8 13:56:11.9966"); //moment I finished this file
 jkl.exactly.howMany.status //2 days, 21 hours, 37 minutes, ...
 jkl.exactly.conversions.status; //0.09 months, 2.9 days, (0.41 weeks), ...
 jkl.rounded.howMany.status; //3 days
 jkl.rounded.conversions.status; //3 days, 72 hours, 4320 minutes, ...
 uio = new Timer(2012, 12, 12, 12, 12, 12, 12); //end of the world!
 uio.rounded.howMany.fireworks(); //takes you to some very nice fireworks
 */

source

Log4r: how to use RollingFileOutputter: automatically cycle stale logfiles

# How to use RollingFileOutputter 

$: << "../src"

require 'log4r'

include Log4r 

puts "this will take a while" 

# example of log file being split by time constraint 'maxtime'

config = {

  "filename" => "logs/TestTime.log",

  "maxtime" => 10,

  "trunc" => true

}

timeLog = Logger.new 'WbExplorer'

timeLog.outputters = RollingFileOutputter.new("WbExplorer", config)

timeLog.level = DEBUG 

# log something once a second for 100 seconds

100.times { |t|

  timeLog.info "blah #{t}"

  sleep(1.0)

} 

# example of log file being split by space constraint 'maxsize'

config = {

  "filename" => "logs/TestSize.log",

  "maxsize" => 16000,

  "trunc" => true

}

sizeLog = Logger.new 'WbExplorer'

sizeLog.outputters = RollingFileOutputter.new("WbExplorer", config)

sizeLog.level = DEBUG 

# log a large number of times

100000.times { |t|

  sizeLog.info "blah #{t}"

} 

puts "done! check the two sets of log files in logs/ (TestTime and TestSize)"

source

Format the current time as an NSString

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"HH:mm:ss"];
	
NSDate *now = [[NSDate alloc] init];

NSString* timeString = [dateFormat stringFromDate:now];	
[dateFormat release];
[now release];

source

time between now and future date. (days, hours, minutes, seconds

function timeBetweenNowAndDeadline($deadline) {
	$currentDate = date("U");
	$diff = $deadline-$currentDate;
	$seconds = 0;
	$hours   = 0;
	$minutes = 0;

	if($diff % 86400 <= 0){$days = $diff / 86400;}  // 86,400 seconds in a day
	if($diff % 86400 > 0)
	{
		$rest = ($diff % 86400);
		$days = ($diff - $rest) / 86400;
		if($rest % 3600 > 0)
		{
			$rest1 = ($rest % 3600);
			$hours = ($rest - $rest1) / 3600;
			if($rest1 % 60 > 0)
			{
				$rest2 = ($rest1 % 60);
			$minutes = ($rest1 - $rest2) / 60;
			$seconds = $rest2;
			}
			else{$minutes = $rest1 / 60;}
		}
		else{$hours = $rest / 3600;}
	}

	if($days > 0){$days = $days.'d, ';}
	else{$days = false;}
	if($hours > 0){$hours = $hours.'h, ';}
	else{$hours = false;}
	if($minutes > 0){$minutes = $minutes.'m, ';}
	else{$minutes = false;}
	$seconds = $seconds.'s'; // always be at least one second

	return $days.''.$hours.''.$minutes.''.$seconds;
}

source

TIME module

## The time module provides a portable interface to time functions on the system on which the program is executing. The following examples illustrate some of the most common uses of the time module.

##The time.time() function returns the current system time in terms of the number of seconds since the UTC (Coordinated Universal Time). This value is typically collected at various points in the program and is used in delta operations to determine the amount of time since an event occurred.
>>>print time.time()
1155333864.11

##The time.localtime(secs) function returns the time, specified by secs since the UTC, in the form of tuple (year, month, day, hour, minute, second, day of week, day of year, daylight savings). If no time is specified, the current time is used as follows:
>>>print time.localtime()
(2006, 8, 11, 16, 4, 24, 4, 223, 1)

##The time.ctime(secs) function returns the time, specified by secs since the UTC, as a formatted, printable string. If no time is specified, then the current time is used as shown here:
>>>print time.ctime()
Fri Aug 11 16:04:24 2006

##The time.clock() function returns the current CPU time as a floating-point number that can be used for various timing functions:
>>>print time.clock()
5.02857206712e-006

##The time.sleep(sec) function forces the current process to sleep for the number of seconds specified by the floating-point number secs:
>>>time.sleep(.5)

source

Thumbnail table with date/time

#!/bin/sh

key=DateTimeOriginal
if [ "$1" = "-k" ]; then
  shift
  key="$1"
  shift
fi

moncmd="montage -label %fn%[EXIF:$key] -geometry 120x120+20+20"

if [ $# -eq 0 ]; then
  echo "usage: thumbindex [-k <EXIF key>] <image file> ..."
  echo "thumbindex generates images containing 25 thumbnails each of the image files given on the command line." | fmt
  exit 0;
fi

pagenr=1

while [ $# -ge 25 ]; do

  for i in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24; do
    thispage[$i]=$1
    shift
  done

  if [ $pagenr -lt 10 ]; then
    $moncmd "${thispage[@]}" thumbindex0$pagenr.jpg
  else
    $moncmd "${thispage[@]}" thumbindex$pagenr.jpg
  fi
  pagenr=$((pagenr+1))

done

if [ $# -eq 0 ]; then
  exit 0
fi

if [ $pagenr -lt 10 ]; then
  $moncmd "$@" thumbindex0$pagenr.jpg
else
  $moncmd "$@" thumbindex$pagenr.jpg
fi

source

generate a mysql BETWEEN clause to find within a date range

def mysql_date_compare(start_date, end_date, col_name = :created_at)
  range_start = (Date.parse(start_date.to_s) - 1.day).strftime("%Y-%m-%d 23:59:59")
  range_end = (Date.parse(end_date.to_s) + 1.day).strftime("%Y-%m-%d 00:00:00")
  "#{col_name.to_s} BETWEEN '#{range_start}' AND '#{range_end}'"
end

source