C#时间与字符串处理函数实用指南

3星 · 超过75%的资源 需积分: 9 4 下载量 19 浏览量 更新于2024-09-17 收藏 14KB TXT 举报
"C#常用函数大集合" 在C#编程语言中,掌握常用的函数是提升编程效率和代码质量的关键。本文将介绍一些在C#中经常使用的函数,包括获取当前时间、字符串转换、数字格式化以及编码处理等。 1. 获取当前时间 在C#中,可以使用`DateTime`类来处理日期和时间。通过创建一个`DateTime`对象并调用其静态方法`Now`,可以获取当前系统时间。例如: ```csharp DateTime currentTime = DateTime.Now; ``` 之后,你可以通过`.Year`, `.Month`, `.Day`, `.Hour`, `.Minute`, `.Second`, 和 `.Millisecond` 属性分别获取年、月、日、小时、分钟、秒和毫秒。 2. 字符串转换 `Int32.Parse()` 方法用于将符合格式的字符串转换为32位整数。例如: ```csharp string strNumber = "123"; int number = Int32.Parse(strNumber); ``` 同时,`DateTime`对象可以使用`ToString()`方法转换为不同格式的字符串,如: ```csharp string strY = currentTime.ToString("f"); // 全格式日期 string strYM = currentTime.ToString("y"); // 年份,短格式 string strMD = currentTime.ToString("m"); // 月份和日期 string strYMD = currentTime.ToString("d"); // 日期,短格式 string strT = currentTime.ToString("t"); // 时间,短格式 ``` 3. 数字格式化 `ToString()` 方法也可以用于数字格式化,例如: ```csharp int num = 12345; string formattedNum = num.ToString("n"); // 12,345.00(带有逗号的数字) string currency = num.ToString("C"); // $12,345.00(货币格式) string exponent = num.ToString("e"); // 1.234500e+004(科学计数法) string fixedPoint = num.ToString("f4"); // 12345.0000(固定小数点) string hex = num.ToString("x"); // 3039(16进制) string percent = num.ToString("p"); // 1,234,500.00%(百分比) ``` 4. 字符串长度 要获取字符串的长度,可以使用`Length`属性。例如: ```csharp string str = "Hello, World!"; int length = str.Length; // 13 ``` 这将返回字符串中字符的数量。 5. 字节编码 `System.Text.Encoding.Default.GetBytes()` 方法用于将字符串转换为字节数组。例如: ```csharp string str = "你好,世界!"; byte[] byteArr = System.Text.Encoding.Default.GetBytes(str); int byteCount = byteArr.Length; ``` 这里,`byteArr`包含了字符串的字节表示,而`byteCount`则给出了字节数组的长度。 这些是C#中的一些基础且实用的函数,熟练掌握它们对于日常开发工作至关重要。继续深入学习C#的其他函数,将有助于你编写更高效、更易读的代码。