TimeStamp & DateTime 互轉函數測試


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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* Author: Zeuxis Lo
* Date : 2009-02-15 22:35 PM
* Title : DateTime & TimeStamp Convert Method Test
*
* Timestamp : 1234567890
* DateTime : 2009-02-14 07:31:30
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Text.RegularExpressions;

namespace timestampConvert {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}

private void btnTimestampToDateTime_Click(object sender, EventArgs e) {
if (String.IsNullOrEmpty(this.txtTimestamp.Text.Trim())) {
MessageBox.Show("Please enter timestamp", "Tips");
return;
}

this.txtDateTime.Text = toDateTime(this.txtTimestamp.Text.Trim());
}

private void btnDateTimeToTimestamp_Click(object sender, EventArgs e) {
if (String.IsNullOrEmpty(this.txtDateTime.Text.Trim())) {
MessageBox.Show("Please enter datetime", "Tips");
return;
}

if (!this.isDateTimeFormat(this.txtDateTime.Text.Trim())) {
MessageBox.Show("Format should be YYYY-mm-dd HH:ii:ss", "Tips");
return;
}

this.txtTimestamp.Text = toTimestamp(this.txtDateTime.Text.Trim());
}

/* Timestamp to DateTime */
private string toDateTime(string timestamp) {
return this.toDateTime(timestamp, 8);
}

private string toDateTime(string timestamp, int timezone) {
DateTime dt = (new DateTime(1970, 1, 1, 0, 0, 0)).AddHours(8).AddSeconds(Convert.ToDouble(timestamp));
return string.Format("{0}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
}

/* DateTime to Timestamp */
private bool isDateTimeFormat(string datetime) {
return Regex.IsMatch(datetime, @"^([0-9]+){1,4}\-([0-9]+){1,2}\-([0-9]+){1,2}\s([0-9]+){1,2}\:([0-9]+){1,2}\:([0-9]+){1,2}$");
}

private string toTimestamp(string datetime) {
return this.toTimestamp(datetime, 0);
}

private string toTimestamp(string datetime, int timezone) {
string[] ymd = datetime.Split(' ')[0].Split('-');
string[] his = datetime.Split(' ')[1].Split(':');

double timestamp = (new DateTime(int.Parse(ymd[0]), int.Parse(ymd[1]), int.Parse(ymd[2]), int.Parse(his[0]), int.Parse(his[1]), int.Parse(his[2])).AddHours(timezone) - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime()).TotalSeconds;
return timestamp + "";
}
}
}