简体   繁体   中英

Convert string to Date format

my string is as follows:

string s ="20000101";

I would like to convert it to Date format. How can I do it?

Assuming you are using C# and .Net you will want to use DateTime.ParseExact or DateTime.TryParseExact . The format string is most likely "yyyyMMdd".

var datestring = "20000101";

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

or

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

If C#/.NET, use DateTime.Parse . If Java, use DateFormat.parse

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

use this to convert time

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms;

namespace DateTimeConvert { public partial class Form1 : Form { public 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>"; } } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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