csharp中DateTime总结-转
Table of Contents
1 时间格式输出
DateTime的ToString(string)方法可以输出各种形式的字符串格式,总结如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms; namespace learning
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Test();
} /// <summary>
/// Description
/// </summary>
public void Test()
{
DateTime dateValue = DateTime.Now;
// Create an array of standard format strings.
string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o",
"R", "s", "t", "T", "u", "U", "y", ""};
// Output date and time using each standard format string.
StringBuilder str = new StringBuilder(); foreach (string standardFmt in standardFmts)
{
str.Append(String.Format("{0}: {1}", standardFmt,
dateValue.ToString(standardFmt)));
str.Append("\r\n");
}
this.textBox1.Text = str.ToString(); /*
// Create an array of some custom format strings.
string[] customFmts = {"h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f",
"dd MMM HH:mm:ss", @"\Mon\t\h\: M", "HH:mm:ss.ffffzzz" };
// Output date and time using each custom format string.
foreach (string customFmt in customFmts)
{
str.Append(String.Format("'{0}': {1}", customFmt,
dateValue.ToString(customFmt)));
str.Append("\r\n");
}
this.textBox1.Text = str.ToString();
*/
} }
}
/*
d: 2013-1-18
D: 2013年1月18日
f: 2013年1月18日 11:33
F: 2013年1月18日 11:33:37
g: 2013-1-18 11:33
G: 2013-1-18 11:33:37
m: 1月18日
o: 2013-01-18T11:33:37.3125000+08:00
R: Fri, 18 Jan 2013 11:33:37 GMT
s: 2013-01-18T11:33:37
t: 11:33
T: 11:33:37
u: 2013-01-18 11:33:37Z
U: 2013年1月18日 3:33:37
y: 2013年1月
: 2013-1-18 11:33:37 'h:mm:ss.ff t': 11:31:22.60 上
'd MMM yyyy': 18 一月 2013
'HH:mm:ss.f': 11:31:22.6
'dd MMM HH:mm:ss': 18 一月 11:31:22
'\Mon\t\h\: M': Month: 1
'HH:mm:ss.ffffzzz': 11:31:22.6093+08:00
*/
2 求某天是星期几
由于DayOfWeek返回的是数字的星期几,我们要把它转换成汉字方便我们阅读,有些人可能会 用switch来一个一个地对照,其实不用那么麻烦的,
/// <summary>
/// Description
/// </summary>
public void Test()
{
DateTime dateTime;
dateTime = DateTime.Now;
this.textBox1.Text = day[Convert.ToInt32(dateTime.DayOfWeek)];
}
string[] day = new string[]{ "星期日", "星期一", "星期二", "星期三", "星期四
", "星期五", "星期六" }; // }
3 字符串转换为DateTime
用DateTime.Parse(string)方法,符合"MM/dd/yyyy HH:mm:ss"格式的字符串, 如果是某些特殊格式字符串,就使用DateTime.Parse(String, IFormatProvider)方法。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Globalization; namespace learning
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Test();
} /// <summary>
/// Description
/// </summary>
private void ShowStr(string str)
{
this.textBox1.Text += str;
this.textBox1.Text += "\r\n";
} /// <summary>
/// Description
/// </summary>
public void Test()
{
// Use standard en-US date and time value
DateTime dateValue;
string dateString = "2/16/2008 12:15:12 PM";
try {
dateValue = DateTime.Parse(dateString);
ShowStr(String.Format("'{0}' converted to {1}.", dateString, dateValue));
}
catch (FormatException) {
ShowStr(String.Format("Unable to convert '{0}'.", dateString));
} // Reverse month and day to conform to the fr-FR culture.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
dateString = "16/02/2008 12:15:12";
try {
dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
ShowStr(String.Format("'{0}' converted to {1}.", dateString, dateValue));
}
catch (FormatException) {
ShowStr(String.Format("Unable to convert '{0}'.", dateString));
} // Parse string with date but no time component.
dateString = "2/16/2008";
try {
dateValue = DateTime.Parse(dateString);
ShowStr(String.Format("'{0}' converted to {1}.", dateString, dateValue));
}
catch (FormatException) {
ShowStr(String.Format("Unable to convert '{0}'.", dateString));
}
}
}
}
3.1 String->DateTime 的弹性做法
利用 DateTime.ParseExact() 方法,只要你知道来源的日期格式,就可以转换。
但是,事情往往没有那么顺利,在使用者输入内容后,从 TextBox 中取出来的字串,不见得 符合你的预期的格式,有可能字串前、中、后多了一些空白、有可能 24 小时制与 12 小时 制搞溷写错了,有可能写【AM 与 PM】而不是【上午与下午】。
幸好 DateTime.ParseExact() 可以做到相当相当地弹性,例如:
string[] DateTimeList = {
"yyyy/M/d tt hh:mm:ss",
"yyyy/MM/dd tt hh:mm:ss",
"yyyy/MM/dd HH:mm:ss",
"yyyy/M/d HH:mm:ss",
"yyyy/M/d",
"yyyy/MM/dd"
};
DateTime dt = DateTime.ParseExact(" 2008/ 3/18 PM 02: 50:23 ",
DateTimeList,
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces
);
宣告一个 String 阵列 DateTimeList,内容值放置所有预期会客制化的日期格式,以符合各 种字串来源;使用 CultureInfo.InvariantCulture 解析各种国别不同地区设定;使用 DateTimesStyles.AllowWhiteSpaces 忽略字串一些无意义的空白。如此一来,即使像 " 2008/3 /18 PM 02: 50:23 " 这么丑陋的字串,也可以成功转到成 DateTime 型态。
4 计算2个日期之间的天数差
DateTime dt1 = Convert.DateTime("2007-8-1");
DateTime dt2 = Convert.DateTime("2007-8-15");
TimeSpan span = dt2.Subtract(dt1);
int dayDiff = span.Days + 1;
5 求本季度第一天
本季度第一天,很多人都会觉得这裡难点,需要写个长长的过程来判断。其实不用的,我 们都知道一年四个季度,一个季度三个月,用下面简单的方法:
/// <summary>
/// Description
/// </summary>
public void Test()
{
// Use standard en-US date and time value
DateTime dateValue = DateTime.Parse("12/12/2012");
string str = dateValue.AddMonths(0 - ((dateValue.Month - 1) % 3)).ToString("yyyy-MM-01");
this.textBox1.Text = str;
}
csharp中DateTime总结-转的更多相关文章
- csharp中DateTime总结
Table of Contents 1 时间格式输出 2 求某天是星期几 3 字符串转换为DateTime 3.1 String->DateTime 的弹性做法 4 计算2个日期之间的天数差 5 ...
- .NET中DateTime.Now.ToString的格式化字符串
.NET中DateTime.Now.ToString显示毫秒:DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") DateTime.N ...
- easyui datagrid中datetime字段的显示和增删改查问题
datagrid中datetime字段的异常显示: 使用过easyui datagrid的应该都知道,如果数据库中的字段是datetime类型,绑定在datagrid显式的时候会不正常显示,一般需要借 ...
- 解决Asp.net Mvc返回JsonResult中DateTime类型数据格式的问题
问题背景: 在使用asp.net mvc 结合jquery esayui做一个系统,但是在使用使用this.json方法直接返回一个json对象,在列表中显示时发现datetime类型的数据在转为字符 ...
- C#中 DateTime , DateTime2 ,DateTimeOffset 之间的小区别 (转载)
闲来无事列了个表比对一下这3兄弟之间还是有一点差距的╮(╯_╰)╭ DateTime DateTime2 DateTimeOffset 日期范围 1753-01-01到 9999-12-31 00 ...
- SQL中DateTime转换成Varchar样式
SQL中DateTime转换成Varchar样式语句及查询结果:Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AMSelect ...
- python中datetime模块中datetime对象的使用方法
本文只讲述datetime模块中datetime对象的一些常用的方法,如果读者需要更多datetime模块的信息,请查阅此文档. datetime模块的对象有如下: timedelta date da ...
- C# WebAPI中DateTime类型字段在使用微软自带的方法转json格式后默认含T的解决办法
原文:C# WebAPI中DateTime类型字段在使用微软自带的方法转json格式后默认含T的解决办法 本人新手,在.Net中写WebAPI的时候,当接口返回的json数据含有日期时间类型的字段时, ...
- 解决python写入mysql中datetime类型遇到的问题
解决python写入mysql中datetime类型遇到的问题 刚开始使用python,还不太熟练,遇到一个datetime数据类型的问题: 在mysql数据库中,有一个datetime类型的字段用于 ...
随机推荐
- 初识CocosCreator的一些问题
本文的cocos creator版本为v1.9.0,除此外大部分都是以v1.9.3版本 1.color赋值 cc.Label组件并没有颜色相关的属性,但是Node有color的属性. //如果4个参数 ...
- json字符串转换对象的方法
为了方便读者了解json的使用,读者直接粘贴下面代码看效果即可: var json1 = {'name':'小李','age':'11','sex':'女'}; console.log(json1.n ...
- Java多线程:AQS
在Java多线程:线程间通信之Lock中我们提到了ReentrantLock是API级别的实现,但是没有说明其具体实现原理.实际上,ReentrantLock的底层实现使用了AQS(AbstractQ ...
- java程序中实现打开 某个指定浏览器
package com.test; import java.lang.reflect.Method; //实现打开浏览器并跳到指定网址的类 public class BareBonesBrowserL ...
- Winform自动更新组件分享
作者:圣殿骑士 出处:http://www.cnblogs.com/KnightsWarrior/ 关于作者:专注于微软平台项目架构.管理和企业解决方案.自认在面向对象及面向服务领域有一定的造诣,熟悉 ...
- canvas应用——将方形图片处理为圆形
上段时间在项目中需要将方形图片处理为圆形图片,你可能会说直接用css设置border-radius: 50%就可以了,但是项目中还要将此图片的圆形图片作为一部分利用canvas将其绘制到一张背景图上面 ...
- UVA11137 Ingenuous Cubrency 完全背包 递推式子
做数论都做傻了,这道题目 有推荐,当时的分类放在了递推里面,然后我就不停的去推啊推啊,后来推出来了,可是小一点的数 输出答案都没问题,大一点的数 输出答案就是错的,实在是不知道为什么,后来又不停的看, ...
- npm install node-sass失败
Cannot download "https://github.com/sass/node-sass/releases/download/v3.8.0/win32-x64-46_bindin ...
- MySQL5.7多主一从(多源复制)同步配置
MySQL5.7多主一从(多源复制)同步配置(抄袭) 原文地址:https://my.oschina.net/u/2399373/blog/2878650 多主一从,也称为多源复制,数据流向: 主库1 ...
- unix缓冲
目的:尽量减少read,write调用的次数. 标准IO提供3种IO: 1.全缓冲.在填满IO缓冲区后才进行实际的IO操作. 2.行缓冲.当输入和输出遇到换行符时,执行IO操作.(设计终端) 3.不带 ...