Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to convert String into Time format used for Time Range?

Tags:

c#

datetime

time

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

    }
}
like image 986
JavaNoob Avatar asked Dec 29 '22 04:12

JavaNoob


1 Answers

    //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

like image 51
abhilash Avatar answered Dec 30 '22 16:12

abhilash