Link to home
Start Free TrialLog in
Avatar of CipherIS
CipherISFlag for United States of America

asked on

C# Format Date assigned to a string

I have a string which is storing a date value 10/30/2015 12:00:00 am.  I need to format it as 20151030.
Avatar of it_saige
it_saige
Flag of United States of America image

This should suffice:
using System;

namespace EE_Q28791680
{
	class Program
	{
		static void Main(string[] args)
		{
			DateTime current = new DateTime(2015, 10, 30);
			Console.WriteLine("The new string representation for {0:MM/dd/yyyy} is {0:yyyyMMdd}", current);
			Console.ReadLine();
		}
	}
}

Open in new window

Which produces the following output -User generated imageYou can read more about Custom Date/Time Formats from here:

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

-saige-
*No Points*

I like the presentation of formatters as laid out on http://blog.stevex.net/string-formatting-in-csharp/
You'll need to convert your string to a DateTime object, and then format that:

String originalDate = "10/30/2015 12:00:00 am";
String format = "MM/dd/yyyy hh:mm:ss tt";
DateTime newDate = DateTime.ParseExact(originalDate, format, CultureInfo.InvariantCulture);

Console.WriteLine(newDate.ToString("yyyyMMdd"));

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of CipherIS
CipherIS
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CipherIS

ASKER

Was the solution that resolved my problem.