DateTime 與時間處理
取得當下時間
DateTime now = DateTime.Now; // 本地時間
DateTime utc = DateTime.UtcNow; // UTC 時間 (推薦儲存/傳輸用)
DateTime today = DateTime.Today; // 今日 00:00:00
元件存取
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 ms = now.Millisecond;
DayOfWeek dow = now.DayOfWeek; // 週幾
int doy = now.DayOfYear; // 第幾天
格式化輸出 (ToString 格式字串)
| 格式 | 說明 | 範例輸出 |
yyyy-MM-dd | 標準日期 | 2024-03-15 |
HH:mm:ss | 24小時制時間 | 14:30:05 |
yyyy-MM-dd HH:mm:ss | 完整日期時間 | 2024-03-15 14:30:05 |
yyyy/MM/dd | 斜線分隔 | 2024/03/15 |
D | 長日期格式 (文化特性) | 2024年3月15日 |
T | 長時間格式 | 下午 02:30:05 |
f | 完整日期時間 (短時間) | 2024年3月15日 下午 02:30 |
o / s | ISO 8601 / 可排序 | 2024-03-15T14:30:05.1234567 |
r | RFC 1123 (HTTP 標頭) | Fri, 15 Mar 2024 06:30:05 GMT |
日期運算
DateTime future = now.AddDays(30);
DateTime past = now.AddMonths(-3);
DateTime specific = new DateTime(2024, 12, 25);
TimeSpan diff = future - now; // 差值
double totalHours = diff.TotalHours;
int days = diff.Days;
// 週期運算
DateTime firstDayOfMonth = new DateTime(now.Year, now.Month, 1);
DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
解析字串
DateTime parsed = DateTime.Parse("2024-03-15"); // 依目前文化特性
DateTime parsed2 = DateTime.ParseExact("15/03/2024", "dd/MM/yyyy", CultureInfo.InvariantCulture);
bool success = DateTime.TryParse(input, out DateTime result); // 安全解析
字串操作核心大全
建立與連接
// 字串插值 (C# 6+, 效能佳、可讀)
string s = $"User: {name}, Age: {age}, Time: {DateTime.Now:HH:mm}";
// StringBuilder (大量連接/迴圈中)
var sb = new StringBuilder();
for (int i = 0; i < 100; i++) sb.AppendLine($"Line {i}");
string result = sb.ToString();
// string.Join (陣列/集合連接)
string csv = string.Join(",", new[] { "A", "B", "C" }); // "A,B,C"
查找與比較
string text = "Hello World";
// 索引查找
int idx = text.IndexOf("World"); // 6 (找不到回傳 -1)
int last = text.LastIndexOf("l"); // 9
bool starts = text.StartsWith("He"); // true
bool ends = text.EndsWith("ld"); // true
bool contains = text.Contains("lo"); // true
// 比較 (忽略大小寫)
bool eq = text.Equals("hello world", StringComparison.OrdinalIgnoreCase);
bool eq2 = string.Equals(text, "HELLO WORLD", StringComparison.OrdinalIgnoreCase);
// 排序比較
int cmp = string.Compare("A", "B", StringComparison.Ordinal); // -1
擷取與移除
string s = "Hello World";
string sub = s.Substring(6); // "World" (從索引 6 到結尾)
string sub2 = s.Substring(6, 3); // "Wor" (長度 3)
// 移除
string removed = s.Remove(5); // "Hello" (索引 5 之後刪除)
string removed2 = s.Remove(5, 6); // "Hello" (索引 5 刪除 6 字元)
// 取代
string replaced = s.Replace("World", "C#"); // "Hello C#"
string multi = s.Replace("l", "L"); // "HeLLo WorLd" (全部取代)
分割與修剪
string csv = "A,B,C, D ,E";
string[] parts = csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
// 結果: ["A", "B", "C", "D", "E"]
string padded = " Hello ";
string trimmed = padded.Trim(); // "Hello"
string trimStart = padded.TrimStart(); // "Hello "
string trimEnd = padded.TrimEnd(); // " Hello"
格式化數值/日期
int num = 12345;
num.ToString("N"); // "12,345.00" (千分位)
num.ToString("C"); // "NT$12,345.00" (貨幣)
num.ToString("X"); // "3039" (十六進位)
num.ToString("D8"); // "00012345" (補零)
double d = 0.1234;
d.ToString("P"); // "12.34%" (百分比)
d.ToString("E"); // "1.234000E-001" (科學記號)
編碼轉換
string text = "中文";
byte[] utf8 = Encoding.UTF8.GetBytes(text);
byte[] unicode = Encoding.Unicode.GetBytes(text); // UTF-16 LE
byte[] bigEndian = Encoding.BigEndianUnicode.GetBytes(text);
string back = Encoding.UTF8.GetString(utf8); // 還原
// Base64
string b64 = Convert.ToBase64String(utf8);
byte[] decoded = Convert.FromBase64String(b64);
集合與 LINQ 必備技巧
List<T> 常用操作
var list = new List { 3, 1, 4, 1, 5 };
list.Add(9);
list.AddRange(new[] { 2, 6 });
list.Insert(0, 0); // 索引 0 插入
list.Remove(1); // 移除第一個 1
list.RemoveAt(0); // 移除索引 0
list.RemoveAll(x => x > 5); // 移除所有 > 5
list.Sort(); // 就地排序
list.Reverse(); // 反轉
bool has = list.Contains(3);
int idx = list.IndexOf(4);
int count = list.Count;
int[] arr = list.ToArray();
Dictionary<TKey, TValue>
var dict = new Dictionary
{
["Apple"] = 1,
["Banana"] = 2
};
dict["Cherry"] = 3; // 新增/更新
bool exists = dict.TryGetValue("Apple", out int val); // 安全取值
dict.Remove("Banana");
foreach (var kvp in dict) { /* kvp.Key, kvp.Value */ }
var keys = dict.Keys;
var values = dict.Values;
LINQ 核心查詢語法 (方法語法)
var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// 篩選
var evens = numbers.Where(n => n % 2 == 0); // 2,4,6,8,10
// 投影
var squares = numbers.Select(n => n * n); // 1,4,9,16,25
// 排序
var desc = numbers.OrderByDescending(n => n); // 10..1
// 分組
var grouped = numbers.GroupBy(n => n % 2); // 兩群:奇/偶
// 聚合
int sum = numbers.Sum();
double avg = numbers.Average();
int max = numbers.Max();
int min = numbers.Min();
// 取前幾筆 / 跳過
var top3 = numbers.Take(3); // 1,2,3
var skip2 = numbers.Skip(2); // 3..10
// 判斷
bool any = numbers.Any(n => n > 5); // true
bool all = numbers.All(n => n > 0); // true
// 轉換
List list = numbers.ToList();
Dictionary dict = numbers.ToDictionary(n => n, n => n * 10);
HashSet set = numbers.ToHashSet();
// 連接 (Join)
var users = new[] { new { Id = 1, Name = "A" }, new { Id = 2, Name = "B" } };
var orders = new[] { new { UserId = 1, Amount = 100 }, new { UserId = 1, Amount = 200 } };
var q = users.Join(orders, u => u.Id, o => o.UserId, (u, o) => new { u.Name, o.Amount });
LINQ 查詢語法 (SQL 風格)
var result = from n in numbers
where n % 2 == 0
orderby n descending
select n * n;
// 編譯器轉換為方法語法,效能相同
常用類別靜態方法速查
| 類別 | 方法 | 用途 |
Path | Combine, GetFileName, GetExtension, GetDirectoryName, GetTempFileName | 路徑操作 (跨平台安全) |
File | ReadAllText, WriteAllText, ReadAllLines, Exists, Copy, Move, Delete | 檔案整體讀寫 |
Directory | CreateDirectory, Exists, GetFiles, GetDirectories, Delete | 目錄操作 |
Environment | GetFolderPath, GetEnvironmentVariable, MachineName, ProcessorCount, TickCount | 系統環境資訊 |
Guid | NewGuid(), Parse(), TryParse() | 唯一識別碼 |
Convert | ToBase64String, FromBase64String, ToInt32, ChangeType | 型別轉換、編碼 |
Math | Max, Min, Abs, Round, Ceiling, Floor, Pow, Sqrt, Random | 數學運算 |
Regex | IsMatch, Match, Matches, Replace, Split | 正則表達式 |
結語
熟練掌握上述 API,能解決 90% 以上的日常開發需求。建議:
- 優先使用 LINQ 表達資料轉換邏輯,減少手寫迴圈
- 字串大量操作用 StringBuilder,單行插值用
$""
- 日期儲存用 UTC,顯示時轉本地時區
- 編碼統一用 UTF-8,避免 BigEndianUnicode 除非協定要求
- 善用 Try 系列方法 (
TryParse, TryGetValue) 避免例外控制流程