Developer
Developer

Reputation: 8636

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?

Upvotes: 1

Views: 10075

Answers (4)

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>";
        }
    }
} }

Upvotes: -2

Matthew Whited
Matthew Whited

Reputation: 22433

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

Upvotes: 8

Randolpho
Randolpho

Reputation: 56381

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

Upvotes: 0

dublev
dublev

Reputation: 4385

in C/C++, use the time.h (ctime) library's gmtime function, after converting the time to an integer: tm =gmtime(atoi(time_string));

Upvotes: 0

Related Questions