Một số hàm xử lý ngày tháng

21 10 2009

Hàm kiểu DateTime dùng để tìm kiếm ngày bất kì. Có thể tìm được ngày bắt đầu và ngày kết thúc của một năm. untitled.bmp

Hàm kiểu DateTime dùng để tìm kiếm ngày bất kì. Có thể tìm được ngày bắt đầu và ngày kết thúc của một năm (cả năm nhuận).

Đây là hàm để tìm ra ngày “hôm qua” và “ngày mai”

static class DateHelpers

{

// Hàm tìm ngày hôm qua

static public DateTime GetYesterday()

{

DateTime yesterday = DateTime.Today.AddDays(-1);

Console.WriteLine(“Yesterday: ” + yesterday.ToShortDateString());

return yesterday;

}

}

“Ngày mai” và “hôm nay”

static class DateHelpers

{

static public void ShowToday()

{

// ngày hôm nay

DateTime today = DateTime.Today;

Console.WriteLine(“Today: ” + today.ToShortDateString());

}

static public DateTime GetTomorrow()

{

// ngày mai

DateTime tomorrow = DateTime.Today.AddDays(1);

Console.WriteLine(“Tomorrow: ” + tomorrow.ToShortDateString());

return tomorrow;

}

}

Ngày đầu tiên của năm

static public DateTime FirstDayOfYear()

{

return FirstDayOfYear(DateTime.Today);

}

//ngày đầu tiên của năm với tham số ngày được truyền vào

FirstDayOfYear(DateTime selectedDay)

{

DateTime firstDay = DateTime.Parse(selectedDay.Year.ToString() + “-01-01″);

Console.WriteLine(“First of this year: ” + firstDay.ToShortDateString());

return firstDay;

}

Ngày cuối cùng của năm (Lưu ý năm nhuận)

//ngày cuối cùng của năm hiện tại

static public DateTime LastDayOfYear()

{

return LastDayOfYear(DateTime.Today);

}

// ngày cuối cùng của năm bất kì

static public DateTime LastDayOfYear(DateTime selectedDay)

{

//đầu tiên tìm ra ngày đầu tiên của năm kế tiếp

DateTime firstNextYear = DateTime.Parse(

(selectedDay.Year + 1).ToString() + “-01-01″);

DateTime lastDay = firstNextYear.AddDays(-1);

Console.WriteLine(“Last of this year: ” + lastDay.ToShortDateString());

return lastDay;

}

Một số chú ý

DateTime.Parse
Chuyển đối từ kiểu string sang kiểu DateTime. Trong ví dụ trên tôi thêm vào xâu năm hiện tại xâu “-01-01″ thì đó sẽ là ngày đâu tiên của năm hiện tại. Điều này hiển nhiên đúng.

Overloaded methods
Chúng ta có sử dụng các hàm nạp chồng trong ví dụ trên. Các bạn nhớ lại lý thuyết về nạp chồng phương thức. Đó là các phương thức có cùng tên nhưng khác đối số truyền vào.

ToShortDateString
Hàm này giúp bạn hiển thị kết quả về ngày mà không chứa giờ.


Tác vụ

Thông tin

Gửi phản hồi

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Thay đổi )

Twitter picture

You are commenting using your Twitter account. Log Out / Thay đổi )

Facebook photo

You are commenting using your Facebook account. Log Out / Thay đổi )

Connecting to %s




Follow

Get every new post delivered to your Inbox.