日期及字符串操作

1. 酒店门锁接口调用外边dll里函数参数传入错误引发 ,StartGenerateReportTask: System.Runtime.InteropServices.SEHException: 外部组件发生异常。 

2. 日期处理

方法一:Convert.ToDateTime(string)

string格式有要求,必须是yyyy-MM-dd hh:mm:ss

================================================

方法二:Convert.ToDateTime(string, IFormatProvider)

DateTime dt;

DateTimeFormatInfo dtFormat = new System.GlobalizationDateTimeFormatInfo();

dtFormat.ShortDatePattern = "yyyy/MM/dd";

dt = Convert.ToDateTime("2011/05/26", dtFormat);

================================================

方法二:DateTime.ParseExact()

string dateString = "20110526";

DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

或者

DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);

string mm =  DateTime.Now.ToString("yyyy-MM-dd-ss");

mm = “2006-07-01-06”;

日期格式:yyyyMMdd HH:mm:ss(注意此字符串的字母大小写很严格)
yyyy:代表年份
MM:  代表月份
dd:  代表天
HH:  代表小时(24小时制)
mm:  代表分钟
ss:  代表秒

计算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; 
计算某年某月的天数 
----------------------------------------------- 
int days = DateTime.DaysInMonth(2007, 8); 
days = 31; 
给日期增加一天、减少一天 
----------------------------------------------- 
DateTime dt =DateTime.Now; 
dt.AddDays(1); //增加一天 
dt.AddDays(-1);//减少一天 

3.字符串截取

substring方法

返回位于 String 对象中指定位置的子字符串。

strVariable.substring(startend)
"String Literal".substring(startend)

参数

start

指明子字符串的起始位置,该索引从 0 开始起算。

end

指明子字符串的结束位置,该索引从 0 开始起算。

说明

substring 方法将返回一个包含从 start 到最后(不包含 end )的子字符串的字符串。

substring 方法使用 start 和 end 两者中的较小值作为子字符串的起始点。例如,strvar.substring(0, 3) 和 strvar.substring(3, 0) 将返回相同的子字符串。

如果 start 或 end 为 NaN 或者负数,那么将其替换为0。

子字符串的长度等于 start 和 end 之差的绝对值。例如,在 strvar.substring(0, 3) 和 strvar.substring(3, 0) 返回的子字符串的的长度是 3。

有时候,为了让格式统一,当位数不足时,给予补足。比如:2012-01-01 13:42:05,这其中就对月、日、秒进行了补位。比如IC卡写操作要求写入32位的字符,要存入的信息不满足位数是需要补字符的操作。

在 C# 中可以对字符串使用 PadLeft 和 PadRight 进行补位。

PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度

PadRight(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度

示例:

 a= a.PadLeft(32, '0');

注意第二个参数为 char 类型,所以用单引号,也可以用 Convert.ToChar(string value) 把字符串转换成 char 类型。如果字符串长度大于 1,则使用 str.ToCharArray()[index]。

原文地址:https://www.cnblogs.com/ProgrammerGE/p/2833158.html