WPF数字和字符串处理,日期处理

字符串

字符串占位符拼接

1
string.Format("[{0}] {1}", 10, "abc")

UUID

1
Guid.NewGuid().ToString()

时间戳

1
2
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string timestr = Convert.ToInt64(ts.TotalMilliseconds).ToString();

结果类似于

1648866151124

时间戳

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/// <summary>
/// 返回一个时间戳到毫秒
/// </summary>
/// <returns>
/// </returns>
public static long Timestamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
long timestr = Convert.ToInt64(ts.TotalMilliseconds);
return timestr;
}

/// <summary>
/// 返回一个时间戳到秒
/// </summary>
/// <returns>
/// </returns>
public static long TimestampTotalSeconds()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
long timestr = Convert.ToInt64(ts.TotalSeconds);
return timestr;
}

日期格式化

1
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff dddd"); // => 2016-05-09 13:09:55:2350 星期一

可用于路径

1
2
string timestr = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff");
Console.WriteLine(timestr);

结果类似于

2022-04-02-10-05-02-3485

MD5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
*┌────────────────────────────────────────────────┐
*│ 描 述:MD5Uitls
*│ 作 者:剑行者
*│ 版 本:1.0
*│ 创建时间:2023/2/9 16:59:55
*└────────────────────────────────────────────────┘
*/

namespace ZUtils
{
public class MD5Uitls
{
/// <summary>
/// 字符串MD5加密
/// </summary>
/// <param name="Text">要加密的字符串</param>
/// <returns>密文</returns>
public static string MD5(string Text)
{
byte[] buffer = System.Text.Encoding.Default.GetBytes(Text);
try
{
System.Security.Cryptography.MD5CryptoServiceProvider check;
check = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] somme = check.ComputeHash(buffer);
string ret = "";
foreach (byte a in somme)
{
if (a < 16)
ret += "0" + a.ToString("X");
else
ret += a.ToString("X");
}
return ret.ToLower();
}
catch
{
throw;
}
}
}
}

字符串与字符互转

1
2
3
4
5
6
7
8
9
10
11
12
13
private string getVerfyCode()
{
string mystr = DateTime.Now.ToString("yyyyMMddHH");
char[] cArr = mystr.ToCharArray();
Array.Reverse(cArr);
mystr = "xhkj" + new string(cArr);
mystr = MD5Uitls.MD5(mystr);
if (mystr.Length >= 6)
{
mystr = mystr.Substring(0, 6);
}
return mystr;
}

字符串=>字符数组

1
char[] cArr = mystr.ToCharArray();

字符数组=>字符串

1
new string(cArr);

字符串数组是否包含

1
2
string[] strArr = { "小明", "小红" };
bool isContain = ((IList)strArr).Contains("小明");

Double保留几位小数

不四舍五入

只要求保留2位不四舍五入

1
2
3
4
5
public static double GetDouuble2f(double num)
{
int temp = (int)(num * 100);
return 1.0d * temp / 100;
}

四舍五入

方式1

1
Math.Round(0.55555,2)

方式2

1
decimal d=decimal.Round(decimal.Parse("0.55555"),2);

方式3

1
2
3
4
5
public static double GetDouuble2f(double num)
{
//fN 保留N位,四舍五入
return double.Parse(num.ToString("f2"));
}

方式4

1
2
string  result  =  String.Format("{0:N2}",0.55555);//2位 
string result = String.Format("{0:N3}",0.55555);//3位

方式5

1
2
double s = 55.55555;
string result = s.ToString("#0.00");//点后面几个0就保留几位 55.56

方式6

1
2
3
4
5
6
7
8
9
10
double dValue = 95.12567;
int iValue = 100;
string strValue = "95.12567";
string result = "";

result = Convert.ToDouble(dValue).ToString("0.00");//保留小数点后两位,结果为95.13
result = Convert.ToDouble(iValue).ToString("0.00");//100.00
result = Convert.ToDouble(strValue).ToString("0.00");//95.13
result = Convert.ToDouble(dValue).ToString("P");//得到小数点后2位的百分比,自动 加上%号;//9512.57%
result = Convert.ToDouble(strValue).ToString("f2");//保留小数点后2位; //95.13

Binding使用StringFormat格式化字符串

货币格式

1
<TextBlock Text="{Binding Price, StringFormat={}{0:C}}" /> // $123.46

货币格式,一位小数

1
<TextBox Text="{Binding Price, StringFormat={}{0:C1}}" /> // $123.5

前后文字

前文字

1
<TextBox Text="{Binding Price, StringFormat=单价:{0:C}}" /> //单价:$123.46

后文字

1
<TextBox Text="{Binding Price, StringFormat={}{0}元}" /> // 123.45678元

数字

固定的位数,位数不能少于未格式化前,仅支持整形

1
<TextBox Text="{Binding Count, StringFormat={}{0:D6}}" /> // 086723

指定小数点后的位数

1
<TextBox Text="{Binding Total, StringFormat={}{0:F4}}" /> // 28768234.9329

用分号隔开的数字,并指定小数点后的位数

1
<TextBox Text="{Binding Total, StringFormat={}{0:N3}}" /> // 28,768,234.933

格式化百分比

1
2
3
<TextBox Text="{Binding Persent, StringFormat={}{0:P1}}" /> // 78.9 %

<TextBlock Text="{Binding rate, StringFormat={}{0:F2}%}"/> // 78.66%

自定义格式化

整数不保留小数点后数字,小数才保留。

格式化转换类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Globalization;

namespace SchoolClient.ValueConverters
{
internal class NumConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double num = (double)value;
double num2 = double.Parse(parameter.ToString());

int temp_num = (int)Math.Pow(10.0, num2);
double temp_num2 = (double)(int)(num * temp_num) / temp_num;
return temp_num2 + "%";
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}

XAML中

原来的

1
<TextBlock Text="{Binding rate, StringFormat={}{0:f2}%}" />

替换为

1
2
3
4
5
6
<Window xmlns:conv="clr-namespace:SchoolClient.ValueConverters">
<Window.Resources>
<conv:NumConverter x:Key="num_conv" />
</Window.Resources>
<TextBlock Text="{Binding Path=rate, Converter={StaticResource num_conv}, ConverterParameter='2'}" />
</Window>

占位符

1
2
<TextBox Text="{Binding Price, StringFormat={}{0:0000.00}}" /> // 0123.46
<TextBox Text="{Binding Price, StringFormat={}{0:####.##}}" /> // 123.46

日期/时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:d}}" /> // 5/4/2015
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:D}}" /> // Monday, May 04, 2015
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:f}}" /> // Monday, May 04, 2015 5:46 PM
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:F}}" /> // Monday, May 04, 2015 5:46:56 PM
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:g}}" /> // 5/4/2015 5:46 PM
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:G}}" /> // 5/4/2015 5:46:56 PM
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:m}}" /> // May 04
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:M}}" /> // May 04
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:t}}" /> // 5:46 PM
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:T}}" /> // 5:46:56 PM
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:yyyy年MM月dd日}}" /> // 2015年05月04日
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:yyyy-MM-dd}}" /> // 2015-05-04
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:yyyy-MM-dd HH:mm}}" /> // 2015-05-04 17:46
<TextBox Text="{Binding DateTimeNow, StringFormat={}{0:yyyy-MM-dd HH:mm:ss}}" /> // 2015-05-04 17:46:56

或者

1
<TextBlock Text="{Binding Time,StringFormat='yyyy:MM:dd HH:mm:ss'}"/>

多重绑定

1
2
3
4
5
6
<TextBox.Text>
<MultiBinding StringFormat="姓名:{0}{1}">
<Binding Path="FristName" />
<Binding Path="LastName" />
</MultiBinding>
</TextBox.Text>

结果

姓名:AAbb

多重绑定中的特殊字符

1
2
3
4
5
6
<TextBox.Text>
<MultiBinding StringFormat="姓名:{0}&#x09;{1}">
<Binding Path="FristName" />
<Binding Path="LastName" />
</MultiBinding>
</TextBox.Text>

特殊符号

1
2
3
4
5
6
7
\a  &#x07;  BEL
\b &#x08; BS - Backspace
\f &#x0c; FF - Formfeed
\n &#x0a; LF, NL - Linefeed, New Line
\r &#x0d; CR - Carriage return
\t &#x09; HT - Tab, Horizontal Tabelator
\v &#x0b; VT - Vertical Tabelator

结果

姓名:AA bb