C#.net format time string to achieve different display effect _ Practical tips

Source: Internet
Author: User
Tags iso 8601 local time string format truncated
Sometimes we have to change the time to achieve different display effects.
The default format is: 2005-6-6 14:33:34
What if you want to change into a 200506,06-2005,2005-6-6 or more?
We need to use: DateTime.ToString method (String, IFormatProvider)

Using System;
Using System.Globalization;
String format= "D";
DateTime Date=datatime,now;
Response.Write (date. ToString (format, datetimeformatinfo.invariantinfo));
Result output
Thursday, June 16, 2005

Parameter format format verbose usage
Format Character Association attribute/description
D ShortDatePattern-----08/30/2006
D Longdatepattern-----Wednesday, August 2006
F Full Date and time (long date and short time)-----Wednesday, August 2006 23:21
F Fulldatetimepattern (long date and long time)-----Wednesday August 2006 23:22:02
G General (short date and short time)-----08/30/2006 23:22
G General (short date and long time)-----08/30/2006 23:23:11
M, M Monthdaypattern
R, R Rfc1123pattern
s use local time Sortabledatetimepattern (based on ISO 8601)
T shorttimepattern------23:24
T longtimepattern-------23:24:30
U universalsortabledatetimepattern format for displaying Universal Time-------2006-08-30 23:25:10z
U use the full date and time of the universal Time (long date and long time)-----Wednesday, August 2006 15:25:37
Y, y Yearmonthpattern

The following table lists the patterns that can be merged to construct custom schemas. These patterns are case-sensitive; for example, "MM" is recognized, but "MM" is not recognized. If the custom pattern contains white space characters or characters enclosed in single quotes, the output string page will also contain those characters. Characters that are not defined as part of a format pattern or that are not defined as format characters are copied verbatim.

Format Pattern Description
D One day of the month. The date of one number does not have a leading zero.
One day of DD month. The date of a single number has a leading zero.
The abbreviated name of a day in the DDD week, defined in Abbreviateddaynames.
dddd the full name of the day of the week, defined in DayNames.
M-month numbers. A single number of months does not have a leading zero.
MM month number. A one-digit month has a leading zero.
The abbreviated name of the MMM month, defined in AbbreviatedMonthNames.
The full name of the MMMM month, defined in MonthNames.
Y does not contain the year of the era. If the year that does not contain the era is less than 10, the year is displayed with no leading zeros.
YY does not contain years of the era. If the year that does not contain the era is less than 10, the year with leading zeros is displayed.
YYYY includes the four-digit year of the era.
GG period or ERA. If the date to be formatted does not have an associated period or era string, the pattern is ignored.
H 12 Hour system. The number of hours in a single digit does not have a leading zero.
HH 12-hour hour. The number of hours in a single digit has a leading zero.
H 24 hour system. The number of hours in a single digit does not have a leading zero.
HH 24-hour hour. The number of hours in a single digit has a leading zero.
M minutes. The number of minutes in one digit does not have a leading zero.
MM minutes. The number of minutes in a single digit has a leading zero.
s seconds. A number of seconds does not have a leading zero.
SS seconds. The number of seconds in a single digit has a leading zero.
The fractional precision of f seconds is one digit. The remaining digits are truncated.
The fractional precision of FF seconds is two digits. The remaining digits are truncated.
The decimal precision for fff seconds is three digits. The remaining digits are truncated.
The decimal precision for ffff seconds is four digits. The remaining digits are truncated.
The decimal precision for fffff seconds is five digits. The remaining digits are truncated.
The decimal precision for ffffff seconds is six digits. The remaining digits are truncated.
The decimal precision for fffffff seconds is seven digits. The remaining digits are truncated.
t the am/pm defined in AMDesignator or PMDesignator indicates the first character of the item, if one exists.
The AM/PM indication (if any) that TT is defined in AMDesignator or PMDesignator.
Z Time zone offset ("+" or "-" followed only by hours). The number of hours in a single digit does not have a leading zero. For example, the Pacific Standard Time is "-8".
The ZZ Time zone offset ("+" or "-" follows only the hour). The number of hours in a single digit has a leading zero. For example, the Pacific Standard Time is "-08".
ZZZ Full time zone offset ("+" or "-" followed by hours and minutes). The number of hours and minutes for a single digit has a leading zero. For example, the Pacific Standard Time is " -08:00".
: The default time separator defined in TimeSeparator.
/the default date separator defined in DateSeparator.
% c where C is the format pattern (if used alone). If the format pattern is merged with a literal character or another format pattern, you can omit the "%" character.
\ c where c is any character. Display characters according to the literal meaning. To display the backslash character, use "\".

Only the format patterns listed in the second table above can be used to create custom patterns; The standard format characters listed in the first table cannot be used to create custom patterns. The length of the custom pattern is at least two characters;

DateTime.ToString ("D") returns the DateTime value, and "D" is the standard short date pattern.
DateTime.ToString ("%d") returns the day of the month, and "%d" is a custom pattern.
DateTime.ToString ("D") returns the day of the month followed by a blank character, and "D" is a custom pattern.

It is convenient that the above parameters can be arbitrarily combined, and do not go wrong, try more, you will find the time format
To get the time of June 2005 in such a format
You can write this:
Date. ToString ("YYYY year mm month", Datetimeformatinfo.invariantinfo)
So the analogy

Date. ToString ("Yyyy/mm/dd HH:mm:ss", Datetimeformatinfo.invariantinfo)

Today
DateTime.Now.Date.ToShortDateString ();
Yesterday, is today's date minus one
DateTime.Now.AddDays (-1). ToShortDateString ();
Tomorrow, by the same token, add a
DateTime.Now.AddDays (1). ToShortDateString ();

This week, knowing that the first day of the week is the day of the week, knowing that the first day of the week is a few days ago, note that every week is from Sunday to Saturday.
DateTime.Now.AddDays (Convert.todouble (0-convert.toint16 (DateTime.Now.DayOfWeek))). ToShortDateString ();
DateTime.Now.AddDays (Convert.todouble (6-convert.toint16 (DateTime.Now.DayOfWeek))). ToShortDateString ();
If you do not understand, and then look at the Chinese to show the day of the week should understand the way
Because DayOfWeek returns the number of days of the week, we have to convert it to Chinese characters to facilitate our reading, some people may use switch to one by one to control, in fact, not so troublesome
string[] Day = new string[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
Day[convert.toint16 (DateTime.Now.DayOfWeek)];

Last week, the same thing, a week is 7 days, last week is this week minus 7 days, and next week is the same
DateTime.Now.AddDays (Convert.todouble (0-convert.toint16 (DateTime.Now.DayOfWeek))-7). ToShortDateString ();
DateTime.Now.AddDays (Convert.todouble (6-convert.toint16 (DateTime.Now.DayOfWeek))-7). ToShortDateString ();
Next week
DateTime.Now.AddDays (Convert.todouble (0-convert.toint16 (DateTime.Now.DayOfWeek)) + 7). ToShortDateString ();
DateTime.Now.AddDays (Convert.todouble (6-convert.toint16 (DateTime.Now.DayOfWeek)) + 7). ToShortDateString ();
This month, many people will say that the first day of this month is definitely number 1th, the last day is next month, one more day. Of course, it's right.
The general wording
DateTime.Now.Year.ToString () + DateTime.Now.Month.ToString () + "1"; First day
DateTime.Parse (DateTime.Now.Year.ToString () + DateTime.Now.Month.ToString () + "1"). Addmonths (1). AddDays (-1). ToShortDateString ()/Last day

It's easier to format the characters in C # with ToString
DateTime.Now.ToString ("yyyy-mm-01");
DateTime.Parse (DateTime.Now.ToString ("yyyy-mm-01")). Addmonths (1). AddDays (-1). ToShortDateString ();

Last month, minus a month
DateTime.Parse (DateTime.Now.ToString ("yyyy-mm-01")). Addmonths (-1). ToShortDateString ();
DateTime.Parse (DateTime.Now.ToString ("yyyy-mm-01")). AddDays (-1). ToShortDateString ();
Next month, add a month.
DateTime.Parse (DateTime.Now.ToString ("yyyy-mm-01")). Addmonths (1). ToShortDateString ();
DateTime.Parse (DateTime.Now.ToString ("yyyy-mm-01")). Addmonths (2). AddDays (-1). ToShortDateString ();
7 days later
DateTime.Now.Date.ToShortDateString ();
DateTime.Now.AddDays (7). ToShortDateString ();
7 days ago
DateTime.Now.AddDays (-7). ToShortDateString ();
DateTime.Now.Date.ToShortDateString ();

This year, it's easy to figure out the first and last days of the year with the characters of ToString.
DateTime.Parse (DateTime.Now.ToString ("yyyy-01-01")). ToShortDateString ();
DateTime.Parse (DateTime.Now.ToString ("yyyy-01-01")). Addyears (1). AddDays (-1). ToShortDateString ();
Last year, there's no need to explain.
DateTime.Parse (DateTime.Now.ToString ("yyyy-01-01")). Addyears (-1). ToShortDateString ();
DateTime.Parse (DateTime.Now.ToString ("yyyy-01-01")). AddDays (-1). ToShortDateString ();
Next year
DateTime.Parse (DateTime.Now.ToString ("yyyy-01-01")). Addyears (1). ToShortDateString ();
DateTime.Parse (DateTime.Now.ToString ("yyyy-01-01")). Addyears (2). AddDays (-1). ToShortDateString ();

This quarter, many people will feel the difficulty here, need to write a long process to judge. In fact, we all know that four quarters a year, a quarter of three months
First we push the date to the first month of the quarter, and the first day of the month is the first day of the quarter.
DateTime.Now.AddMonths (0-((datetime.now.month-1)% 3)). ToString ("yyyy-mm-01");
Similarly, the last day of the quarter is the first day of the next quarter minus a
DateTime.Parse (DateTime.Now.AddMonths (3-(datetime.now.month-1)% 3)). ToString ("yyyy-mm-01")). AddDays (-1). ToShortDateString ();
Next quarter, I'm sure you all know .... Wrap
DateTime.Now.AddMonths (3-((datetime.now.month-1)% 3)). ToString ("yyyy-mm-01");
DateTime.Parse (DateTime.Now.AddMonths (6-(datetime.now.month-1)% 3)). ToString ("yyyy-mm-01")). AddDays (-1). ToShortDateString ();
Last quarter
DateTime.Now.AddMonths ( -3-((datetime.now.month-1)% 3)). ToString ("yyyy-mm-01");
DateTime.Parse (DateTime.Now.AddMonths (0-(datetime.now.month-1)% 3)). ToString ("yyyy-mm-01")). AddDays (-1). ToShortDateString ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.