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

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

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

Substring functions in XSLT

Examples of string functions (substring,substring-after, and substring-before) in XSLT.
substring("ready1234",2,4)
=> eady 
substring("ready1234", 4)
=> dy1234

substring-after("ready1234","y")
=> 1234

substring-before("ready1234","1")
=> ready


reference: X Lab: String functions [zvong.org]

Setting a string variable with a mult-line text value

This example demonstrates how easy it is to copy and paste human-readable text from elsewhere and declare it as a string in your code.

string = <<RUBY_RUBY_RUBY
  <mydoc>
    <someelement attribute="nanoo">Text, text, text</someelement>
  </mydoc>
RUBY_RUBY_RUBY



Note: Remember to encase the text within a pair of strings, any string (the convention is to make it uppercase) and ensure it's not a reserved keyword, or a variable declared already.

Convert a string to a character array

// converts a string into a character array, then displays the output 1 character at a time from the array.

y = 'testing'.scan(/./)
y.each do |c|
	puts c
end
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS