IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » date The latest public date snipts.

showing 1-20 of 46 snipts for date
  • euler_project_19
    #!/usr/bin/env python
    
    def cYearCode (n):
        result_d4 = n / 4
        result_m7 = n % 7
        return (result_d4 + result_m7) % 7
    
    def cDayCode (n):
        return (n % 7)
    
    monthcode = [0,3,3,6,1,4,6,2,5,0,3,5]
    day = ["sun", "mon", "tue", "wed","thu","fri","sat"]
    
    year = 2000
    month = 3
    date = 1
    
    code = (cYearCode (year - 1900) +monthcode[month] + cDayCode(1)) % 7
            
    if (year - 1900) % 4 == 0 and month <= 1:
        code -= 1
    print day[code]
    
    
    """
    sum = 0
    for year in range(1901,2001):
        for month in range(12):
            code = (cYearCode (year - 1900) +monthcode[month] + cDayCode(1)) % 7
            
            if (year - 1900) % 4 == 0 and month <= 1:
                code -= 1
            if code == 0:
                sum += 1
                
    print sum
    """
    

    copy | embed

    0 comments - tagged in  posted by dgg32 on Aug 11, 2010 at 3:26 p.m. EDT
  • A class that help you to convert dates to and from unix date format from .net datetime class
    /// <summary>
    /// Convertions between DateTime and unix time representations
    /// </summary>
    public class TimeHelper
    {
            /// <summary>
    	/// The base time 01/01/1970 12:00 am
    	/// </summary>
    	static DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
    
    	/// <summary>
    	/// Covert the current date to the miliseconds  01/01/1970 12:00 am 
    	/// </summary>
    	/// <param name="current">The date to convert</param>
    	/// <returns>miliseconds  since 01/01/1970 12:00 am</returns>
    	public static string CFNormalization(DateTime current)
    	{
    		return (long)(current.Subtract(baseTime)).TotalMilliseconds+"";
    
    	}
    
    	/// <summary>
    	/// Convert from milisecond since 01/01/1970 12:00 am to DateTime
    	/// </summary>
    	/// <param name="miliseconds">The milisecond to convert</param>
    	/// <returns>DateTime that represent the date since 01/01/1970 12:00</returns>
    	public static DateTime CFDenormalization(long miliseconds)
    	{
    		return baseTime.AddMilliseconds(miliseconds);
    
    	}
    
    }
    

    copy | embed

    0 comments - tagged in  posted by dilaang on May 20, 2010 at 11:08 a.m. EDT
  • Add date and time to every command listed in Bash history
    :> ~/.bash_history
    history -c
    export HISTTIMEFORMAT='%F %T    '
    

    copy | embed

    0 comments - tagged in  posted by d1s4st3r on May 04, 2010 at 8:39 a.m. EDT
  • Sort by custom field date
    <?php
    //The Query
    // exactly than
    query_posts('meta_key=start_date&meta_value='.date("Y-m-d"));
    // or
    // dates less than
    // query_posts('meta_key=start_date&meta_compare=<=&meta_value='.date("Y-m-d"));
    // or
    // date mayor than
    // query_posts('meta_key=start_date&meta_compare=>=&meta_value='.date("Y-m-d"));
     
    //The Loop
    if ( have_posts() ) : while ( have_posts() ) : the_post();
     echo the_title();
     echo "<br />";
    endwhile; else:
     
    endif;
     
    //Reset Query
    wp_reset_query();
    ?>
    

    copy | embed

    0 comments - tagged in  posted by panprojektant on Apr 27, 2010 at 4:23 p.m. EDT
  • como comparar date e datetime
    #---------------------------------------
    #
    # italo mc maia
    # data: 26/04/2010
    # website: http://italomaia.com
    # twitter: http://twitter.com/italomaia
    # 
    #---------------------------------------
    
    from datetime import date, datetime
    
    # o truque esta no formato da string
    today = date.today().strftime("%Y%m%d")
    now = datetime.now().strftime("%Y%m%d")
    
    # OU - agradecimentos ao Alisson Sales
    # today = date.today().toordinal()
    # now = datetime.now().toordinal()
    
    today == now # dá o resultado esperado
    today != now # dá o resultado esperado
    today < now # dá o resultado esperado
    today > now  # dá o resultado esperado
    today <= now # dá o resultado esperado
    today >= now # dá o resultado esperado
    
     
    

    copy | embed

    0 comments - tagged in  posted by italomaia on Apr 26, 2010 at 10:52 p.m. EDT
  • Convert MM/DD/YYYY date to YYYY-MM-DD with PHP
    <?
    function convertDate($date) {
    	$date = preg_replace('/\D/','/',$date);
    	return date('Y-m-d',strtotime($date));
    }
    
    print convertDate('11/05/1996'); //prints 1996-11-05
    ?>
    

    copy | embed

    0 comments - tagged in  posted by bradrozier on Apr 26, 2010 at 3:48 p.m. EDT
  • Calculate the difference between dates in on column within the same table
    SELECT DATEDIFF(
     (SELECT DATE(date_field) FROM table WHERE id = '1' AND status_id = '2' ORDER BY date_field DESC LIMIT 1),
     (SELECT DATE(date_field) FROM table WHERE id = '1' AND status_id = '1' ORDER BY date_field DESC LIMIT 1)
    	) AS difference
    

    copy | embed

    0 comments - tagged in  posted by bradrozier on Apr 26, 2010 at 3:44 p.m. EDT
  • Adjusts timezone and sets am or pm for a stored date.
    	//this is just a standard mysql datetime
    	$start_dte = '0000-00-00 00:00:00';	
    	$timestamp = mktime(substr($start_dte,11,2), substr($start_dte,14,2), 0, substr($start_dte,5,2), substr($start_dte,8,2), substr($start_dte,0,4));
    	//adjust the time here by adding or subtracting seconds from the timestamp
    	$timestamp = $timestamp + 12540;
    	//convert back to date format
    	$timestamp = date('Y-m-d H:i:s', $timestamp);	
    	
    	$HouR = substr($timestamp,11,2);
    	$PotD = 'am';
    	if($HouR > 12){
    		$HouR = $HouR - 12;
    		$PotD = 'pm';	
    	}
    
    	echo "".substr($timestamp,5,2)."/".substr($timestamp,8,2)."/".substr($timestamp,2,2)." ".$HouR.":".substr($timestamp,14,2)." ".$PotD."";
    	//returns mm/dd/yy hh:mm am
    

    copy | embed

    0 comments - tagged in  posted by gilbogger on Mar 20, 2010 at 2:14 p.m. EDT
  • Determine the earliest business day, taking business hour into consideration.
    <?php
    function next_business_date() {
    	$min = time();
    	
    	// Past cut-off time, make it the next day.
    	if (date('H', $min) >= '17')
    	{
    		$min += 86400; // +24 Hours
    	}
    	
    	// If it falls on weekend, make it Monday.
    	$day_of_week = date('N', $min);
    	if ($day_of_week == '6')
    	{
    		$min += 172800;
    	}
    	elseif ($day_of_week == '7')
    	{
    		$min += 86400;
    	}
    	
    	return strtotime(date('Y-m-d', $min));
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Mar 07, 2010 at 11:52 a.m. EST
  • Converting from date to epoch time
    #!/usr/bin/perl
    use Time::Local
     
    $time = timelocal($sec,$min,$hour,$mday,$mon,$year);
    $time = timegm($sec,$min,$hour,$mday,$mon,$year);
    
    # Allowed range values
    
    #    * day of the month: 1..31
    #    * month: 0..11 (0 = January, 1 = February, etc)
    #    * year:
    #          o If value>999: the value is interpreted as the actual year
    #          o If value is 100..999: the value is interpreted as an offset #from 1900 (for example, 199 is considered year 2099)
    #          o If value is 0..99: the value is interpreted based on the current year: if the current year is in the second half of the century #(for example 1970), then the values in the range 50..99 are considered of be in the current century and the values in the range 0..49 are in the next century. If the current year is in the first half of the century (for example 2007), then the range 0..49 is interpreted as values in the current century and the range 50..99 is interpreted as years from the #previous century.
    

    copy | embed

    0 comments - tagged in  posted by yvoictra on Jan 25, 2010 at 4:29 p.m. EST
  • Dates Samples
    <?php
    
    $currDate = date('Y-m-d h:i:s');
    
    // convert timestamp from mysql
    $nextReviewDt = date('F d, Y',strtotime($nextReviewDt));
    
    // Add 30 days 
    $CommentStartDt = date('m/d/Y');
    $CommentEndDt = date('m/d/Y', 
    	mktime(0,0,0,date("m"),date("d")+30,date("Y"))); // add 30 days
    
    // convert year to 4 digits
    if ($y > 60) $y = '19'.$y;
    else $y = '20'.$y;
    
    // split if there are slash or dash
    list($m, $d, $y) = split('[/|-]', $iDate);
    
    if (preg_match("/-/", $iDate))
    	list($m, $d, $y) = split('-', $iDate);
    else if (preg_match("/\//", $iDate))
    	list($m, $d, $y) = split('/', $iDate);
    
    $specDate = mktime(0, 0, 0, $m, $d, $y);
    $numOfDays = (time() - $specDate) / (24 * 60 * 60);
    
    // convert date from mysql db
    if (preg_match("/(.*)Dt$/", $dbDate))
    	$dbDate = date("M d, Y h:ia", strtotime($dbDate));
    
    // output dates - walk the days
    $startDt = '2009-01-04';
    $endDt = date('Y-m-d');
    while ($startDt != $endDt)
    {
    	echo "$startDt <br/>";
    	// increment the day
    	$startDt = strtotime(date("Y-m-d", strtotime($startDt)) . " +1 day");
    	// convert back to readable format
    	$startDt = date("Y-m-d",$startDt);
    }
    
    function count_days( $a, $b )
    {
    	// First we need to break these dates into their constituent parts:
    	$gd_a = getdate( $a );
    	$gd_b = getdate( $b );
    
    	// Now recreate these timestamps, based upon noon on each day
    	// The specific time doesn't matter but it must be the same each day
    	$a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
    	$b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
    
    	// Subtract these two numbers and divide by the number of seconds in a
    	//  day. Round the result since crossing over a daylight savings time
    	//  barrier will cause this time to be off by an hour or two.
    	return round( abs( $a_new - $b_new ) / 86400 );
    }
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Jan 22, 2010 at 3:28 p.m. EST
  • Getting actual date in Perl
    $DDMMYYHHMMSS = sprintf("%02d/%02d/%04d %02d:%02d:%02d", sub{($_[3],$_[4]+1,$_[5]+1900,$_[2],$_[1]),$_[0]}->(localtime(time())));
    

    copy | embed

    0 comments - tagged in  posted by yvoictra on Jan 14, 2010 at 6:40 p.m. EST
  • date datetime picker jQuery UI for Rails
    $(document).ready(function() {
        // Define the dateFormat for the datepicker
        $.datepicker._defaults.dateFormat = 'dd M yy';
    
        /**
         * Sets the date for each select with the date selected with datepicker
         */
        $('input.ui-date-text').live("change", function() {
            var sels = $(this).siblings("select:lt(3)");
            var d = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $(this).val() );
            
            $(sels[0]).val(d.getFullYear());
            $(sels[1]).val(d.getMonth() + 1);
            $(sels[2]).val(d.getDate());
        });
        
        /**
         * Replaces the date or datetime field with jquey-ui datepicker
         */
        $('.date, .datetime').each(function(i, el) {
            var input = document.createElement('input');
            $(input).attr({'type': 'text', 'class': 'ui-date-text'});
            // Insert the input:text before the first select
            $(el).find("select:first").before(input);
            $(el).find("select:lt(3)").hide();
            // Set the input with the value of the selects
            var values = [];
            $(input).siblings("select:lt(3)").each(function(i, el) {
                var val = $(el).val();
                if(val != '')
                    values.push(val);
            });
            if( values.length > 1) {
                d = new Date(values[0], parseInt(values[1]) - 1, values[2]);
                $(input).val( $.datepicker.formatDate($.datepicker._defaults.dateFormat, d) );
            }
    
            $(input).datepicker();
        });
    });
    

    copy | embed

    1 comment - tagged in  posted by boriscy on Nov 30, 2009 at 2:09 p.m. EST
  • little date dealy for converting mysql date fomats to mm/yy/dd
    $dt = '0000-00-00 00:00:00';
    ".substr($dt,5,2)."/".substr($dt,8,2)." //dd/mm
    ".substr($dt,11,2).":".substr($dt,14,2)." //hh:mm
    

    copy | embed

    0 comments - tagged in  posted by gilbogger on Oct 27, 2009 at 9:47 p.m. EDT
  • date in italian format
    function today() {
    	var dt= new Date();
    	dt.setDate(dt.getDate());
    	var yyyy = dt.getFullYear();
    	var mm = ('0' +	parseInt(dt.getMonth()+1).toString()).slice(-2);
    	var dd = ('0' + dt.getDate().toString()).slice(-2);
    	return dd+'/'+mm+'/'+yyyy;	
    }
    

    copy | embed

    0 comments - tagged in  posted by CorPao on Oct 19, 2009 at 3:43 p.m. EDT
  • PHP script file last modification data
    //echo script file last modification data
    echo date('d/m/y',filemtime($_SERVER['SCRIPT_FILENAME'])); 
    

    copy | embed

    0 comments - tagged in  posted by matt_dunckley on Oct 01, 2009 at 11:12 a.m. EDT
  • echo days in this month
    <?
    //echo days in this month
    //set up date variables
    $d_date = date('d', time());
    $M_date = date('M', time());
    $m_date = date('m', time());
    $y_date = date('y', time());
    $Y_date = date('Y', time());
    $days_in_this_month = date( "d", mktime(0, 0, 0, $m_date + 1, 0, $Y_date) );
    echo $days_in_this_month;
    ?>
    

    copy | embed

    0 comments - tagged in  posted by matt_dunckley on Oct 01, 2009 at 11:08 a.m. EDT
  • bash month test
    [ `date --date='next day' +'%B'` == `date +'%B'` ] || echo 'fim do mês'
    
    # o trecho antes da dupla igualdade retorna o mês do dia de amanhã,
    # já o trecho após a dupla igualdade retorna o mês do dia de hoje, caso # # sejam diferentes o bash avisa que você está no fim do mês. 
    

    copy | embed

    0 comments - tagged in  posted by voyeg3r on Sep 29, 2009 at 8:35 a.m. EDT
  • Regex: Date format
    <?
    // Date must match format: mm/dd/yyyy
    if (!preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $due_date))
      echo "Error !";
    

    copy | embed

    0 comments - tagged in  posted by robertbanh on Sep 15, 2009 at 3:38 p.m. EDT
  • Fecha en formato String YYYYMMDD
    DateTimeVariable.ToString("yyyyMMdd")
    

    copy | embed

    0 comments - tagged in  posted by ghporras on Sep 02, 2009 at 4:00 p.m. EDT
Sign up to create your own snipts, or login.