字符串转换为日期格式

问题描述:

我的字符串如下:字符串转换为日期格式

string s ="20000101"; 

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

+7

什么编程语言使用的是? – Jamey 2010-08-04 16:36:23

+0

@Jamey:好点。我假定C#是因为使用小写'string'的一般语法。对'Date'对象的请求意味着Java,但它应该是'String'。 C++有'string',但没有像'Date'或'DateTime'对象。 – Randolpho 2010-08-04 16:41:17

+1

他的大部分问题都是关于'C#'的,所以这可能是一个安全的假设。 – 2010-08-04 16:42:59

假设您使用的是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 
+0

嗨,我无法削减它可以给你的确切代码 – Dotnet 2010-08-04 16:42:10

+0

@Dorababu,增加了两个例子。 – 2010-08-04 16:43:38

+0

但我越来越在格式dd/mm/yy,我不需要时间戳 – Dotnet 2010-08-04 16:46:25

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

+0

注意:我假设C#是因为小写字符串类型。如果是另一种语言,请相应编辑您的问题。 – Randolpho 2010-08-04 16:38:38

+0

在C#只有我在做 – Dotnet 2010-08-04 16:42:27

在C/C++

,使用time.h中(的ctime)库的gmtime的功能,时间转换为整数后:tm =gmtime(atoi(time_string));

使用这个转换时间

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

命名空间DateTimeConvert { 公共部分Form1类:形式 { 公共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>"; 
     } 
    } 
} }