今天、昨天、前天、明天
class Program
{
static void Main(string[]
args)
{
DateTime
dt1=GetTodayZeroTime(DateTime.Now);
Console.WriteLine("今天零点:{0}",dt1.ToString()
);
DateTime dt2 =
GetYestodayZeroTime(DateTime.Now);
Console.WriteLine("昨天零点:{0}",
dt2.ToString());
DateTime dt3 =
GetDayBeforYestodayZeroTime(DateTime.Now);
Console.WriteLine("前天零点:{0}",
dt3.ToString());
DateTime dt4 =
GetTomorrowZeroTime(DateTime.Now);
Console.WriteLine("明天零点:{0}",
dt4.ToString());
Console.ReadLine();
}
private static
DateTime GetTodayZeroTime(DateTime
datetime)
{
return
new DateTime(datetime.Year, datetime.Month,
datetime.Day);
}
private static DateTime
GetYestodayZeroTime(DateTime
datetime)
{
TimeSpan
timespan = new TimeSpan(1, 0, 0,
0);
DateTime yesdt =
datetime.Subtract(timespan);
return new DateTime(yesdt.Year, yesdt.Month,
yesdt.Day);
}
private static DateTime
GetDayBeforYestodayZeroTime(DateTime
datetime)
{
TimeSpan
timespan = new TimeSpan(2, 0, 0,
0);
DateTime yesdt =
datetime.Subtract(timespan);
return new DateTime(yesdt.Year, yesdt.Month,
yesdt.Day);
}
private static DateTime
GetTomorrowZeroTime(DateTime
datetime)
{
TimeSpan
timespan = new TimeSpan(1, 0, 0,
0);
DateTime yesdt =
datetime.Add(timespan);
return new DateTime(yesdt.Year, yesdt.Month,
yesdt.Day);
}
}
本文来自网络上朋友们的帖子,这里进行了一个汇总
取一个月的最后一天日期
int yy = 2005;
int mm
= 11;
int Lastday =
DateTime.DaysInMonth(yy, mm);
另一种方法
int year = 2005;
int month =
11;
DateTime dt = new
DateTime(year,month,1).AddMonths(1).AddDays(-1);
取某一天所在周的最后一天日期
String date = "2007-09-27 ";
SimpleDateFormat
sdf = new SimpleDateFormat( "yyyy-MM-dd
");
Calendar calendar = new
GregorianCalendar();
calendar.setTime(sdf.parse(date));
calendar.set(Calendar.DAY_OF_WEEK,
calendar.getMaximum(Calendar.DAY_OF_WEEK));
System.out.println(sdf.format(calendar.getTime()));
时间比较:
DateTime date1 = new DateTime(2009, 8, 1, 0, 0,
0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0,
0);
int result = DateTime.Compare(date1,
date2);
string relationship;
if (result
< 0)
relationship = "is earlier
than";
else if (result ==
0)
relationship = "is the same time
as";
else
relationship = "is later
than";
Console.WriteLine("{0} {1} {2}", date1,
relationship, date2);
// The example displays the following
output:
// 8/1/2009 12:00:00 AM is earlier
than 8/1/2009 12:00:00 PM
时间比较:
while (DateTime.Compare(dtBegin, dtEnd) <=
0)
{
//
//循环主体
//
dtBegin =
dtBegin.AddHours(1);
//时间相加
}
时间相减:
TimeSpan ts =
endtime.Subtract(begintime).Duration();