Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
If I have a string such as :

<filename>_yyyymmdd.csv

Note that <filename> varies.

How do I get the yyyymmdd into a date format using c# please?
Posted
Updated 10-Feb-12 16:44pm
v2

You will need to use regex or string mashing to get your date out. Then if it's always this format, I am not sure if DateTime.TryParse will work, or if you need to string mash further to get out 3 numbers, use int.TryParse on all of them and then build a datetime from there.
 
Share this answer
 
Comments
arkiboys 10-Feb-12 11:51am    
Yes, but not sure how to get the date.
Christian Graus 10-Feb-12 11:55am    
I just told you, step by step. You find the _ and the . and extract the string between those two. Then you process it, probably as substrings and integers, because I don't think the parsing will recognise this format ( but you could try ).
If all your file names are in the same format as you have mentioned above, then you can use the following console application code snippet to get the date from the string in to the Date format
C#
using System;
using System.Collections.Generic;
using System.Text;

namespace DateString {
    class Program {
        static void Main(string[] args) {
            string fileName = "fileName_20120210.csv";

            DateTime date;
            int dateStringStart = fileName.LastIndexOf("_")+1;
            int dateStringLength = fileName.LastIndexOf(".")-dateStringStart;
            string dateString = fileName.Substring(dateStringStart, dateStringLength);
            date = new DateTime(Int32.Parse(dateString.Substring(0, 4)),
                                Int32.Parse(dateString.Substring(4, 2)),
                                Int32.Parse(dateString.Substring(6, 2)));

            Console.WriteLine(date);
            Console.ReadKey();
        }
    }
}
 
Share this answer
 
v3
Comments
ProEnggSoft 12-Feb-12 7:20am    
Thank you for the upvote

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900