繁体   English   中英

将字符串转换为日期格式

[英]Convert string to Date format

我的字符串如下:

string s ="20000101";

我想将其转换为日期格式。 我该怎么做?

假设您使用的是C#和.Net,则需要使用DateTime.ParseExactDateTime.TryParseExact 格式字符串很可能是“ yyyyMMdd”。

var datestring = "20000101";

var date1 = DateTime.ParseExact(datestring, "yyyyMMdd", null);

要么

DateTime dateResult;
if (!DateTime.TryParseExact(datestring, "yyyyMMdd", 
                            null, DateTimeStyles.AssumeLocal, 
                            out dateResult))
    dateResult = DateTime.MinValue; //handle failed conversion here

如果是C#/。NET,请使用DateTime.Parse 如果是Java,请使用DateFormat.parse

在C / C ++中,将时间转换为整数后,使用time.h(ctime)库的gmtime函数: tm =gmtime(atoi(time_string));

用它来转换时间

使用系统; 使用System.Collections.Generic; 使用System.ComponentModel; 使用System.Data; 使用System.Drawing; 使用System.Text; 使用System.Windows.Forms;

命名空间DateTimeConvert {公共局部类Form1:Form {公共Form1(){InitializeComponent(); }

  private void button1_Click(object sender, EventArgs e) { label1.Text= ConvDate_as_str(textBox1.Text); } public string ConvDate_as_str(string dateFormat) { try { char[] ch = dateFormat.ToCharArray(); string[] sps = dateFormat.Split(' '); string[] spd = sps[0].Split('.'); dateFormat = spd[0] + ":" + spd[1]+" "+sps[1]; DateTime dt = new DateTime(); dt = Convert.ToDateTime(dateFormat); return dt.Hour.ToString("00") + dt.Minute.ToString("00"); } catch (Exception ex) { return "Enter Correct Format like <5.12 pm>"; } } private void button2_Click(object sender, EventArgs e) { label2.Text = ConvDate_as_date(textBox2.Text); } public string ConvDate_as_date(string stringFormat) { try { string hour = stringFormat.Substring(0, 2); string min = stringFormat.Substring(2, 2); DateTime dt = new DateTime(); dt = Convert.ToDateTime(hour+":"+min); return String.Format("{0:t}", dt); ; } catch (Exception ex) { return "Please Enter Correct format like <0559>"; } } } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM