Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 68 total  RSS 

date_select conversion

function to convert a value from a date_select into a more sql-friendly value

<%=date_select(:date,'',:start_year => 1950,:include_blank => false, :default => { :year => '1970' })%>

def convert_date(obj) 
  return “#{obj[‘(1i)’]}-#{obj[‘(2i)’]}-#{obj[‘(3i)’]}” 
end

Convert Java date to GMT

This function converts a local date to GMT. This version corrects the bug common to this type of conversion where the date is incorrectly converted when the time is close to the DST crossover.

private static Date cvtToGmt( Date date )
{
   TimeZone tz = TimeZone.getDefault();
   Date ret = new Date( date.getTime() - tz.getRawOffset() );

   // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
   if ( tz.inDaylightTime( ret ))
   {
      Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

      // check to make sure we have not crossed back into standard time
      // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
      if ( tz.inDaylightTime( dstDate ))
      {
         ret = dstDate;
      }
   }

   return ret;
}

Days since January 1st, 2008

// I'm in a challenge to do one pushup and one crunch for each day of the new year. This little Ruby snippet will tell me how many I have to do!

(DateTime.now - DateTime.new(2008,1,1)).to_i

Rails Date Formats

// cribbed from http://wiki.rubyonrails.org/rails/pages/HowToDefineYourOwnDateFormat

my_formats = {
  :my_format_1 => '%l %p, %b %d, %Y',
  :my_format_2  => '%l:%M %p, %B %d, %Y'
}

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(my_formats)
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(my_formats)

Increment a date using Ruby

This Ruby code converts a string into a date and increments the day, week, month, quarter or year.

def date_add(sdate='', unit='',i=0)

  sdate[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/]
  iyear = $3.to_i; imonth = $2.to_i; iday = $1.to_i; ihour = $4.to_i; imin = $5.to_i; isec = $6.to_i
  
  case  unit
    when 'days'
      t1 = Time.local(iyear,imonth,iday,ihour,imin,isec)
      t1 += (60 * 60 * 24 * i)
    when 'weeks'
      t1 = Time.local(iyear,imonth,iday,ihour,imin,isec)
      t1 += (60 * 60 * 24 * 7 * i) 
    when 'months'
      imonth += i
      if imonth < 12 then
        t1 = Time.local(iyear,imonth+i,iday,ihour,imin,isec)
      else
        t1 = Time.local(iyear+=1,imonth -12,iday,ihour,imin,isec)
      end
    when 'quarter'
      imonth += 3
      if imonth <= 12 then
        t1 = Time.local(iyear,imonth,iday,ihour,imin,isec)
      else
        t1 = Time.local(iyear+=1,imonth - 12,iday,ihour,imin,isec)
      end    
    when 'years'
      t1 = Time.local(iyear+i,imonth,iday,ihour,imin,isec)
    else
      raise 'not a valid date unit'
  end
  t1
end

date_add("17/03/2008 17:48:00",'months',2)

output: Sat May 17 17:48:00 +0100 2008

Creating a DateTime object with Ruby

This example creates a date and time variable which represents 22nd March 2008 4:30pm and 12 seconds.
d2 = DateTime.new(y=200,m=3,d=22, h=16,min=30,s=12)

or convert a date string into a DataTime object:
"17/03/2009 17:48:00"[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/]
d2 = DateTime.new(y=$3.to_i,m=$2.to_i,d=$1.to_i, h=$4.to_i,min=$5.to_i,s=$6.to_i)

or convert a date string into a Time object:
"22/03/2008 17:48:00"[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/]
iyear = $3.to_i; imonth = $2.to_i; iday = $1.to_i; ihour = $4.to_i; imin = $5.to_i; isec = $6.to_i
twork = Time.local(iyear,imonth,iday,ihour,imin,isec) 
puts 'we still have time to party' if Time.now < twork 

Reference:
Class: DateTime [ruby-doc.org]
Class: Time [ruby-doc.org]

Calculate last day of current Month

'Determines what the next month is based on today and subtracts 1 day from first day of next month.

'VB.NET
Dim NextMonth As Integer
Dim RptYear As Integer
'Determine next month
NextMonth = DatePart(DateInterval.Month, DateAdd(DateInterval.Month, +1, today))
'Determine the year of the next month, in case you are going from Dec to Jan
RptYear = DatePart(DateInterval.Year, DateAdd(DateInterval.Month, +1, today))
'Subtract 1 day from the first day of next month to get this months last day
Return DateAdd(DateInterval.Day, -1, DateValue(NextMonth.ToString & "/1/" & RptYear.ToString))

isWorkingDay?

// description of your code here

  public boolean isWorkingDay(Date date) {
        Calendar cal = GregorianCalendar.getInstance();
        cal.setTime(date);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); 
        if ((dayOfWeek  Calendar.SATURDAY) || (dayOfWeek  Calendar.SUNDAY)) {
            return false;
        } 
        return true;
   }

Calculate Last Day of Last Month

VB/VBA/VB.NET one-liner to calculate the end of last month. Useful for SSRS/RDL Expressions and Excel/Office Formulas. Note that it does not use string parsing, which can cause localization problems.


DateAdd("d", -1.0 * DatePart("d", Today), Today)

Calculate First Day of Current Month

VB/VBA/VB.NET one-liner to calculate the start of the current month. Useful for SSRS/RDL Expressions and Excel/Office Formulas. Note that it does not use string parsing, which can cause localization problems.

DateAdd("D", -1.0 * DatePart("D", Today) + 1, Today)
« Newer Snippets
Older Snippets »
Showing 1-10 of 68 total  RSS