字符串转换为日期格式
答
假设您使用的是C#和.Net,您将需要使用DateTime.ParseExact或DateTime.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/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>"; } } } }
什么编程语言使用的是? – Jamey 2010-08-04 16:36:23
@Jamey:好点。我假定C#是因为使用小写'string'的一般语法。对'Date'对象的请求意味着Java,但它应该是'String'。 C++有'string',但没有像'Date'或'DateTime'对象。 – Randolpho 2010-08-04 16:41:17
他的大部分问题都是关于'C#'的,所以这可能是一个安全的假设。 – 2010-08-04 16:42:59