日常开发里有大量与数据格式转换相关的小需求:Base64 编解码、Unix 时间戳互转、敏感字段打码展示。把它们收进一个静态工具类,能避免每个项目重复造轮子。

完整代码

using System;
using System.Text;

public static class TextHelper
{
    /// 字符串转 Base64
    public static string Base64Encode(string s) =>
        Convert.ToBase64String(Encoding.UTF8.GetBytes(s));

    /// Base64 还原字符串
    public static string Base64Decode(string s) =>
        Encoding.UTF8.GetString(Convert.FromBase64String(s));

    /// DateTime 转 Unix 秒时间戳
    public static long ToTimestamp(DateTime dt) =>
        (long)(dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;

    /// Unix 秒时间戳转本地时间
    public static DateTime FromTimestamp(long ts) =>
        DateTimeOffset.FromUnixTimeSeconds(ts).ToLocalTime().DateTime;

    /// 手机号中间四位打码
    public static string MaskPhone(string phone)
    {
        if (string.IsNullOrEmpty(phone) || phone.Length < 11) return phone;
        return phone.Substring(0, 3) + "****" + phone.Substring(7);
    }
}

调用示例

TextHelper.MaskPhone("13800138000") 返回 138****8000;TextHelper.Base64Encode("你好") 得到 UTF-8 编码后的标准 Base64 串,适合对接口签名或登录态做轻量混淆。

注意

  • Base64 只是编码不是加密,传输敏感信息仍需 HTTPS 与签名;
  • 时间戳互转务必统一为 UTC 基准,避免不同时区机器解析错位;
  • 打码逻辑要按业务长度做防御,号码异常时原样返回比抛异常更友好。

小结

把零散格式转换收敛成静态工具类后,页面与接口代码会更干净,也能在测试中集中覆盖这些边界情况。