Displaying posts categorized under

Datetime

C# Datediff

 
When you are in need of the VB datediff in your C# project you have two options:
You can either add a reference to Microsoft.VisualBasic and access the DateDiff function like this:

long nYears = Microsoft.VisualBasic.DateAndTime.DateDiff(Microsoft.VisualBasic.DateInterval.Year,
dt, dtNow,
Microsoft.VisualBasic.FirstDayOfWeek.System,
Microsoft.VisualBasic.FirstWeekOfYear.System);

Or you need to write your own function – in C#:

using System;
using System.Collections.Generic;
using System.Text;

namespace datediffdemo
{
public enum [...]

Convert string to datetime

This is a favorite function I used a lot when getting data from remote systems. For example I once needed to retrieve data from an AS/400 box, and the file format was already specified. However, date fields in the file could look pretty different (6, 8, 10 digits with or without delimiters between year/month/day), depending [...]

Getting datetime for last day of a month

To get the last day in a month from a datetime value is not too hard either but you need to do a little trick:
First get the first day, add one month from that, and then subscract one day from that:
 

Getting datetime for first day of month

To get the first day in a month from a datetime value is of course very simple:

public static DateTime GetFirstInMonth(DateTime dt)
{
DateTime dtRet = new DateTime(dt.Year, dt.Month, 1, 0,0,0); return dtRet;
}