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 17 total  RSS 

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)

Calculate First Day of Last Month

VB/VBA/VB.NET one-liner to calculate the start of the previous 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, DateAdd("m", -1, Today))

DateTime to double and vice versa

 public static double ToDouble(DateTime what)
 {
  return BitConverter.ToDouble(BitConverter.GetBytes(what.Ticks), 0);
 }

 public static DateTime ToDateTime(double what)
 {
  return new DateTime(BitConverter.ToInt64(BitConverter.GetBytes(what), 0));
 }

Display DateTime up to milliseconds

Format string "ffff" is responsible for displaying milliseconds.

 string myTime = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff");
 Console.WriteLine(myTime);

Set Date & Time

public struct SystemTime
{
 public ushort Year;
 public ushort Month;
 public ushort DayOfWeek;
 public ushort Day;
 public ushort Hour;
 public ushort Minute;
 public ushort Second;
 public ushort Millisecond;
};

[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
public extern static void Win32GetSystemTime(ref SystemTime st);

[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
public extern static bool Win32SetSystemTime(ref SystemTime st);

....

public static void Test()
{
 SystemTime newTime = new SystemTime();
 newTime.Year = (ushort)2005;
 newTime.Month = (ushort)12;
 newTime.Day = (ushort)2;
 newTime.Hour = (ushort)12; //UTC time (if you are in UTC+2 zone then you'll put here: time - 2h)
 newTime.Minute = (ushort)42;
 newTime.Second = (ushort)11;
 Win32SetSystemTime(ref newTime);
}

SQL Reporting Services Date Conversion

// A single line function to convert a date from one format to another.

=System.DateTime.ParseExact(Parameters!lic_period_start_date.Value,"dd/MM/yyyy",System.Globalization.DateTimeFormatInfo.InvariantInfo).ToString("yyyyMMdd")

Fix for ActiveRecord SQL Server adapter dates

The SQL Server adapter for ActiveRecord uses Time objects to cast dates from the db. This fails for dates before 1970, thus some birthdates come back as nil. This is some kludge to use a DateTime in that case so we still get the value.

A better approach may be to convert this code to use DateTime objects exclusively, but I'm not sure of the speed implications of doing so. The code below first tries to cast the value to a Time object; if that fails, it tries a DateTime object; if that fails, it returns nil.

Stick this in a plugin to use with Rails.

module ActiveRecord
  module ConnectionAdapters
    class ColumnWithIdentity
      def cast_to_time(value)
        return value if value.is_a?(Time) or value.is_a?(DateTime)
        time_array = ParseDate.parsedate(value)
        time_array[0] ||= 2000
        time_array[1] ||= 1
        time_array[2] ||= 1
        Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
      end
      def cast_to_datetime(value)
        if value.is_a?(Time) or value.is_a?(DateTime)
          if value.year != 0 and value.month != 0 and value.day != 0
            return value
          else
            return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
          end
        end
        return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
        value
      end
    end
  end
end

Another simple datetime+struct_time class

I had shown how datetime can be used in python 2.2
in a previous snippet. Still, it's sometimes too big.

Here's a minimal implementation. It works like both
datetime and stuct_time (as returned by localtime() and gmtime()).
import time

class datetime(object):
    def __init__(self, *argv):
        self.t = time.struct_time(argv+(0,)*(9-len(argv)))    # append to length 9 
    def __getattr__(self, name):
        try:
            i = ['year', 'month', 'day', 'hour', 'minute', 'second', 'weekday'].index(name)
            return self.t[i]
        except:
            return getattr(self.t, name)
    def __len__(self): return len(self.t)
    def __getitem__(self, key): return self.t[key]
    def __repr__(self): return repr(self.t)
    def now(self=None):
        return datetime(*time.localtime())
    now = staticmethod(now)
    def strftime(self, fmt="%Y-%m-%d %H:%M:%S"):
        return time.strftime(fmt, self.t)

Here's its usage
# here it works like datetime.datetime()
>>> t = datetime.now()
>>> t.year, t.month, t.day
(2006, 3, 13)
>>> t.hour, t.minute, t.second
(23, 3, 28)

# but also works like localtime()
>>> t
(2006, 3, 13, 23, 3, 28, 0, 72, -1)
>>> t.tm_year, t[0]
(2006, 2006)
>>> mktime(t)
1142265808.0

# good default for strftime (= ctime)
>>> t.strftime()
'2006-03-13 23:03:28'

Using datetime in python 2.2 (e.g. pys60)

Python 2.2 doesn't have a decend date/time class.
There's a small compatible library from the Python Web Project.

I download the source and extract the datetime.py then
send it to my phone as a pys60 library.
Here's a simple test that works well.
(Taken from Effbot)
>>> import datetime
>>> now = datetime.datetime(2003, 8, 4, 12, 30, 45)
>>> print now
2003-08-04 12:30:45
>>> print repr(now)
datetime.datetime(2003,8,4,12,30,45)
>>> print type(now)
<type 'instance'>
>>> print now.year, now.month, now.day
2003 8 4
>>> print now.hour, now.minute, now.second
12 30 45

See its documentation here.
One limitation as a library is that you need to use
datetime.datetime(2004,1,1).now() # work for any version

instead of just
datetime.datetime.now() # python 2.3+


update
======
I add 'staticmethod' expression. Now it works fine.
    def now(self=None):
        "Return the current date and time as a datetime."
        now = t.localtime()
        return datetime(now[0],now[1],now[2],now[3],now[4],now[5])
    now = staticmethod(now)
« Newer Snippets
Older Snippets »
Showing 1-10 of 17 total  RSS