首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 常用工具函數精選:DateTime、字串格式化、編碼轉換與數值處理

     編輯:關於ASP.NET

DateTime 日期時間操作

// 取得目前時間
DateTime now = DateTime.Now;           // 本地時間
DateTime utcNow = DateTime.UtcNow;     // UTC 時間

// 元件擷取
int year = now.Year;
int month = now.Month;
int day = now.Day;
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;
int millisecond = now.Millisecond;
DayOfWeek dow = now.DayOfWeek;         // 週幾

// 格式化輸出
string iso = now.ToString("yyyy-MM-ddTHH:mm:ss.fff");  // 2024-01-15T14:30:45.123
string tw = now.ToString("yyyy/MM/dd HH:mm:ss");       // 2024/01/15 14:30:45
string dateOnly = now.ToString("yyyy/MM/dd");
string timeOnly = now.ToString("HH:mm:ss");

// 運算
DateTime tomorrow = now.AddDays(1);
DateTime lastMonth = now.AddMonths(-1);
TimeSpan diff = DateTime.Now - startTime;
double totalHours = diff.TotalHours;

// 解析
bool ok = DateTime.TryParse("2024/01/15 14:30", out DateTime parsed);
DateTime exact = DateTime.ParseExact("15/01/2024", "dd/MM/yyyy", CultureInfo.InvariantCulture);

數值與字串互轉

// 字串 → 數值
int i = int.Parse("12345");
long l = long.Parse("1234567890123");
double d = double.Parse("3.14159");
bool success = int.TryParse("abc", out int result);  // 安全轉換,失敗回傳 false

// 數值 → 字串格式化
int num = 12345;
num.ToString("N")      // "12,345.00"   千分位 + 2 位小數
num.ToString("C")      // "NT$12,345.00" 貨幣格式 (依 CurrentCulture)
num.ToString("E")      // "1.234500E+004" 科學記號
num.ToString("F4")     // "12345.0000"  固定 4 位小數
num.ToString("X")      // "3039"        十六進位大寫
num.ToString("P")      // "1,234,500.00%" 百分比
num.ToString("000000") // "012345"      補零

// 自訂格式
DateTime dt = DateTime.Now;
dt.ToString("yyyy年MM月dd日 dddd");  // 2024年01月15日 星期一

字串操作實用技巧

string s = "  Hello, World!  ";

// 去除空白
s.Trim();           // "Hello, World!"
s.TrimStart();      // "Hello, World!  "
s.TrimEnd();        // "  Hello, World!"

// 大小寫
s.ToUpper();        // "  HELLO, WORLD!  "
s.ToLower();        // "  hello, world!  "

// 子字串
s.Substring(7, 5);  // "World"
s.Substring(7);     // "World!  "

// 分割與合併
string[] parts = "a,b,c".Split(',', StringSplitOptions.RemoveEmptyEntries); // ["a","b","c"]
string joined = string.Join(" | ", parts); // "a | b | c"

// 取代
s.Replace("World", "ASP.NET"); // "  Hello, ASP.NET!  "

// 判斷
s.Contains("Hello");     // true
s.StartsWith("  He");    // true
s.EndsWith("!  ");       // true
string.IsNullOrWhiteSpace(s); // false

編碼與位元組轉換

string text = "中文測試";

// 字串 → 位元組陣列
byte[] utf8Bytes = Encoding.UTF8.GetBytes(text);
byte[] defaultBytes = Encoding.Default.GetBytes(text);  // 系統預設編碼 (ANSI)
byte[] big5Bytes = Encoding.GetEncoding("big5").GetBytes(text);

// 位元組陣列 → 字串
string fromUtf8 = Encoding.UTF8.GetString(utf8Bytes);
string fromBig5 = Encoding.GetEncoding("big5").GetString(big5Bytes);

// Base64 編解碼
string base64 = Convert.ToBase64String(utf8Bytes);      // "5Lit5paH5a2X5rWL6K+V"
byte[] decoded = Convert.FromBase64String(base64);
string original = Encoding.UTF8.GetString(decoded);

// URL 編解碼
string encoded = HttpUtility.UrlEncode("參數=值&特殊");  // "%E5%8F%83%E6%95%B8%3D%E5%80%BC%26%E7%89%B9%E6%AE%8A"
string decoded2 = HttpUtility.UrlDecode(encoded);

集合與 LINQ 常用模式

var numbers = new[] { 5, 2, 9, 1, 5, 6 };

// 排序
var asc = numbers.OrderBy(n => n);      // 1,2,5,5,6,9
var desc = numbers.OrderByDescending(n => n);

// 篩選
var evens = numbers.Where(n => n % 2 == 0); // 2,6

// 投影
var squares = numbers.Select(n => n * n);   // 25,4,81,1,25,36

// 分組
var groups = numbers.GroupBy(n => n);       // 1→[1], 2→[2], 5→[5,5], 6→[6], 9→[9]

// 聚合
int sum = numbers.Sum();        // 28
double avg = numbers.Average(); // 4.666...
int max = numbers.Max();        // 9
int count = numbers.Count();    // 6

// 字串集合
var names = new[] { "Alice", "Bob", "Charlie" };
string csv = string.Join(",", names);  // "Alice,Bob,Charlie"

檔案路徑與 IO

string path = @"C:\Projects\WebApp\uploads\file.pdf";

Path.GetFileName(path);        // "file.pdf"
Path.GetDirectoryName(path);   // "C:\Projects\WebApp\uploads"
Path.GetExtension(path);       // ".pdf"
Path.GetFileNameWithoutExtension(path); // "file"
Path.Combine("folder", "sub", "file.txt"); // "folder\sub\file.txt"
Path.GetTempFileName();        // 隨機暫存檔路徑
Path.GetTempPath();            // 暫存資料夾路徑

// 實體檔案操作
File.Exists(path);
File.ReadAllText(path);
File.WriteAllText(path, content);
File.Copy(src, dest, overwrite: true);
File.Delete(path);
Directory.CreateDirectory(dir);
Directory.GetFiles(dir, "*.pdf");

總結

掌握 .NET 基礎類別庫的核心 API(DateTime、String、Encoding、Path、LINQ),能大幅減少重複造輪子、避免常見 Bug(編碼錯誤、文化特性差異、NullReference),提升程式碼可讀性與維護性。建議收藏官方文件 System namespace 章節隨時查閱。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved