4

I have a program that is able to retrieve sections/part of a log text file's time using tokenization.

The main aim of the program which is to retrieve the time part then proceed onto converting the string to a DateTime format which could be then used as a part of a Time Range timeline function.

However while converting the time into DateTime, the system outputs the results into "23/11/2010 9:31:00 PM" which correctly converts the time into at 12 Hour format but utilizes the Date function.

Therefore the question would be how to only convert the time and NOT output or process the date. And how can the time be converted into a 24 Hour format into HH:MM:SS?

Please advice on the codes. Thanks!

class Program
{
    static void Main(string[] args)
    {

        //System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("C:\\Test\\ntfs2.txt");

        String value = "Thu Mar 02 1995 21:31:00,2245107,m...,r/rrwxrwxrwx,0,0,8349-128-3,C:/Program Files/AccessData/AccessData Forensic Toolkit/Program/wordnet/Adj.dat";

        //foreach (String r in lines)
        //{

        String[] token = value.Split(',');

        String[] datetime = token[0].Split(' ');

        String timeText = datetime[4]; // The String array contans 21:31:00

        DateTime time = Convert.ToDateTime(timeText); // Converts only the time

        Console.WriteLine(time);

    }
}

6 Answers 6

7
    //System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("C:\\Test\\ntfs2.txt");
    String value = "Thu Mar 02 1995 21:31:00,2245107,m...,r/rrwxrwxrwx,0,0,8349-128-3,C:/Program Files/AccessData/AccessData Forensic Toolkit/Program/wordnet/Adj.dat";

    String[] token = value.Split(',');

    String[] datetime = token[0].Split(' ');

    String timeText = datetime[4]; // The String array contans 21:31:00

    DateTime time = Convert.ToDateTime(timeText); // Converts only the time

    Console.WriteLine(time.ToString("HH:mm:ss"));

You can use DateTime.ToString("pattern") to convert a DateTime to any desired format.

There's a list of patterns available here http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible for the time.ToString to be converted into another DateTime variable lets assume time2 = time.ToString("HH:mm:ss")?
time.ToString("HH:mm:ss") would return a string. so the LValue should be of type string it cannot be assigned to a DateTime.
2

just use this code to convert date time like 5.12 pm to 1712

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];

            if ((sps[1].ToUpper() != "PM") && (sps[1].ToUpper() != "AM"))
            {
                return "Enter Correct Format like <5.12 pm>";
            }

            DateTime dt = new DateTime();
            dt = Convert.ToDateTime(dateFormat);
            string date = "";
            if (sps[1].ToUpper() == "PM")
            {
                date = (dt.Hour + 12).ToString("00");
            }
            else
                date = dt.Hour.ToString("00");
            return date + dt.Minute.ToString("00");
        }
        catch (Exception ex)
        {
            return "Enter Correct Format like <5.12 pm>";
        }

    }

Comments

1
//your log record
string record = "Thu Mar 02 1995 21:31:00,2245107...";

//get the first part - you can include the Thu Mar 02 1995 (datetime can parse)
string date = record.Split(',')[0];

//parse to date time (the Thu Mar 02 doesn't phase dateTime)
DateTime dt = DateTime.Parse(date);

//convert the datetime to a string HH = 24 Hours leading zero, mm = minutes, ss = seconds
string time = dt.ToString("HH:mm:ss");

//write!
Console.WriteLine(time);

edit I see you say don't process the date, this technically processes it - but it's a lot cleaner than splitting up based on spaces and rebuilding the time piece by piece.

3 Comments

DateTime dt = New DateTime(date); Error: Best overloaded method match for ... has some invalid arguments.
DateTime.TryParse could help here
My bad - DateTime.TryParse( .. ..), or if you don't want to error check DateTime.Parse()
0
DateTime x = DateTime.Parse("01/01/2010 10:45 PM");
Console.WriteLine(x.ToString("HH:mm"));

Comments

0

Just use this code to convert string to time

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

Comments

0

Why so hard this is my code:

  private void timer7_Tick(object sender, EventArgs e)
        {
            label4.Text = DateTime.Now.TimeOfDay.Hours.ToString() + ":" + DateTime.Now.TimeOfDay.Minutes.ToString() + ":" + DateTime.Now.TimeOfDay.Seconds.ToString() + ":" + DateTime.Now.TimeOfDay.TotalMilliseconds.ToString();
            label7.Text = DateTime.Now.Date.Year.ToString() + "-" + DateTime.Now.Date.Month.ToString() + "-" + DateTime.Now.Date.Day.ToString();
        }

1 Comment

A little more explanation might help out the fellow programmers to understand how things working around in your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.