[C#] #1 常用變數介紹:int、float、string、List、List int 、List string 、DateTime,時間格式轉換、時間間隔計算、回傳json格式範例,現在時間轉Timestamp、Timestamp轉時間。

Int

Int 名字來源於 Integer, 意思是正數, 範圍為 -2,147,483,648 to 2,147,483,647 [1]

範例:

Int number = 5;

Float

Float 代表一個實數. float 是浮點數值型別。 doubledecimal 也是浮點數值型別. 範圍:

csharp-1-1

Source: [2]

範例:

Float a = 3_000.5F
  • 不帶後綴或帶有 d 或 D 後綴的字面值是 double 型別
  • 帶有 f 或 F 後綴的字面值是 float 型別
  • 帶有 m 或 M 後綴的字面值是 decimal 型別

底線(_)可以作為數字分隔符。適用在各種類型的數字。

String

String 代表文字, String 是 不可變,建立之後無法改變 範例:

string temp = “andrew”;

string s1 = "A string is more ";
string s2 = "than the sum of its chars.";

// 代表s1 是做新的物件
s1 += s2;

System.Console.WriteLine(s1);
// 結果 : A string is more than the sum of its chars.

了解更多關於String, 請往[3]

List, List<int>, List<string>

正確來說是 List<T>, 而 T 是 代表任何一個變數, 可以是 int, float, string 等。 那List 本身是一個T變數的陣列, 也可以透過索引(index)存取的物件列表,以及搜尋、排序和操作列表的方法。[4]

範例1:

List<int> manyNumber; 
manyNumber = new List<int>(); // 宣告一個 list, 製造List 物件

manyNumber.Add(5); // 加入一個數字
manyNumber.Add(6);
manyNumber.Add(7);
manyNumber.Remove(5); // 移除一個數字
manyNumber.Contains(6); // 檢查 6 是否在 list 裡面

// 用 foreach 來走訪 list 裡面的元素
foreach (int number in manyNumber)
{
    Console.WriteLine(number);
}

// 結果 : 
6
7 

範例2:

List<string> students = new List<string>(); // 宣告一個 list, 製造List 物件
students.Add("John"); // 加入一個字串
students.Add("Andrew");
students.Insert(2, "Mary"); // 插入一個字串, (使用Index)
students.RemoveAt(students.Count - 1); // 移除一個字串, (使用Index), students.Count 是 list 裡面的元素數量

// 用 foreach 來走訪 list 裡面的元素
foreach (string student in students)
{
    Console.WriteLine(student);
}

DateTime

代表日期和時間. 平常會存生日日期, 跟檢查相關日期跟時間的變數。

範例

// 當下日期和時間
DateTime now = DateTime.Now;

// 指定日期(年, 月, 日)
DateTime specificDate = new DateTime(2024, 9, 5);

// 指定日期和時間(年, 月, 日, 小時, 分鐘, 秒)
DateTime specificDateTime = new DateTime(2024, 9, 5, 14, 30, 0);

// 從字串轉成日期
DateTime parsedDate = DateTime.Parse("2024-09-05 14:30:00");

// 檢查日期格式是否正確
bool success = DateTime.TryParse("2024-09-05", out DateTime result);
if (success)
{
    Console.WriteLine(result);  // 輸出: 2024/9/5 上午12:00:00
}

時間格式轉換

情況1:從字串轉換到DateTime

範例:

string dateString = "2024-09-05 17:00:00";
DateTime parsedDate = DateTime.Parse(dateString); 

情況2:DateTime 換到string各種格式

簡單介紹一下,<br> 標準格式字串:<br>

  • “d”: 短日期格式(如 01/31/2024)<br>
  • “D”: 長日期格式(如 January 31, 2024)<br>
  • “t”: 短時間格式(如 12:30 AM)<br>
  • “T”: 長時間格式(如 12:30:00 AM)<br>
  • “f”: 完整日期和時間(如 January 31, 2024 12:30 AM)<br>
  • “F”: 完整日期和時間,帶秒數(如 January 31, 2024 12:30:00 AM)<br>
  • “g”: 常見的日期和時間(如 01/31/2024 12:30 AM)<br>
  • “G”: 常見的日期和時間,帶秒數(如 01/31/2024 12:30:00 AM)<br>
  • “O”: 圖表或 ISO 8601 格式(如 2024-01-31T00:30:00.0000000)<br> 自定義格式字串:<br> 可以使用格式化字串來構建自己的格式。常用的格式有:<br>
  • “yyyy”: 四位數年份 <br>
  • “MM”: 月份(兩位數)<br>
  • “dd”: 日期(兩位數)<br>
  • “HH”: 24小時制的小時 <br>
  • “mm”: 分鐘 <br>
  • “ss”: 秒 <br>
  • “fff”: 毫秒 <br> 更多自定義格式請參考 [6]

範例:

DateTime yesterdayTime = DateTime.Now.AddDays(-1); // 取得昨天的日期
yesterdayTime.ToString("yyyy-MM-dd"); // 輸出: 2024-09-04
yesterdayTime.ToString("F"); // 輸出: 2024年9月4日 星期三 下午 5:00:00

情況3: 指定不同文化的日期格式 可以使用 CultureInfo

using System.Globalization;

DateTime now = DateTime.Now;

// 轉換為美國格式
CultureInfo usCulture = new CultureInfo("en-US");
string usFormat = now.ToString("D", usCulture);  // January 31, 2024

// 轉換為法國格式
CultureInfo frCulture = new CultureInfo("fr-FR");
string frFormat = now.ToString("D", frCulture);  // 31 janvier 2024

如果要知道CultureInfo 的 清單, 可以使用以下code [7]

foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
    Console.Write("{0,-7}", ci.Name);
    Console.Write(" {0,-3}", ci.TwoLetterISOLanguageName);
    Console.Write(" {0,-3}", ci.ThreeLetterISOLanguageName);
    Console.Write(" {0,-3}", ci.ThreeLetterWindowsLanguageName);
    Console.Write(" {0,-40}", ci.DisplayName);
    Console.WriteLine(" {0,-40}", ci.EnglishName);
}

時間間隔計算

時間間隔計算是用 TimeSpan 變數來進行計算的。

範例:

DateTime start = new DateTime(2024, 1, 1, 8, 0, 0);  // 開始時間
DateTime end = new DateTime(2024, 1, 1, 17, 30, 0);   // 結束時間


// 計算時間間隔
TimeSpan duration = end - start;

Console.WriteLine(duration.TotalHours);  // 計算整個時間間隔的總小時數, 輸出: 9.5
Console.WriteLine(duration.Hours);  // 只計算時間間隔中 "小時" 這個部分 輸出: 9

Console.WriteLine(duration.TotalMinutes);  // 計算整個時間間隔的總分鐘數, 輸出: 570
Console.WriteLine(duration.Minutes);  // 只計算時間間隔中 "分鐘" 這個部分 輸出: 30

Console.WriteLine(duration.TotalSeconds);  // 計算整個時間間隔的總秒數, 輸出: 34200
Console.WriteLine(duration.Seconds);  // 只計算時間間隔中 "秒" 這個部分 輸出: 0

了解TimeSpan更多請往 [8]

JSON 格式

JavaScript Object Notation (JSON) 是結構化的JavaScript 物件的標準格式[5]。 在ASP.NET Web API, Swagger 裡面, 輸入跟回傳資料都是 JSON 格式的。

JSON格式範例:

{
  "rid": 0,
  "rName": "string"
}

用文字來說明JSON 存在以下4個規則:

  • 數據以名稱/值對形式存在
  • 數據以逗號分隔
  • 大括號包含物件
  • 方括號包含陣列

Swagger範例

csharp-1-2

這是請求(Request)主體是以JSON格式

csharp-1-3

回傳(Response) 也是以JSON格式

Timestamp

我們先了解一下Timestamp 是什麼, Timestamp 或者 Unix Timestamp 是一種時間表示方式, 從UTC1970年1月1日0時0分0秒起至現在的總秒數 [9]

現在時間轉Timestamp

範例:

// 獲取當前時間
DateTime noww = DateTime.UtcNow;

// 將當前時間轉換為 Unix Timestamp, 使用DateTimeOffset是因為要找跟UTC相差多少時鐘
long timestamp = new DateTimeOffset(noww).ToUnixTimeSeconds();

// 輸出結果
Console.WriteLine("Current Unix Timestamp: " + timestamp);

## Timestamp轉時間
// 假設你有一個 Unix Timestamp,例如 1725813107
long unixTimestamp = 1725813107;

// 將 Unix Timestamp 轉換為 DateTimeOffset
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp);

// 將 DateTimeOffset 轉換為本地時間
DateTime dateTime = dateTimeOffset.LocalDateTime;

// 輸出結果
Console.WriteLine("Converted DateTime: " + dateTime);

有一個網站可以轉換TimeStamp跟時間, https://www.unixtimestamp.com/

References

[1] https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types

[2] https://learn.microsoft.com/zh-tw/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types

[3] https://learn.microsoft.com/zh-tw/dotnet/csharp/programming-guide/strings/

[4] https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-8.0

[5] https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Objects/JSON

[6] https://learn.microsoft.com/zh-tw/dotnet/standard/base-types/custom-date-and-time-format-strings

[7] https://stackoverflow.com/questions/15968625/culture-info-names

[8] https://learn.microsoft.com/zh-tw/dotnet/api/system.timespan?view=net-8.0

[9] https://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4