How to convert any date format to yyyy-MM-dd - c#

My app parses a string data, extracts the date and identify the format of the date and convert it to yyyy-MM-dd.
The source date could be anything lime dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.
Other than attempting different permutations and combinations using switch case, is there any other efficient way to do it?
string sourceDate = "31-08-2012";
String.Format("{0:yyyy-MM-dd}", sourceDate);
The above code simply returns the same sourceDate "31-08-2012".

string DateString = "11/12/2009";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);
These Links might also Help you
DateTime.ToString() Patterns
String Format for DateTime [C#]

Convert your string to DateTime and then use DateTime.ToString("yyyy-MM-dd");
DateTime temp = DateTime.ParseExact(sourceDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = temp.ToString("yyyy-MM-dd");

string sourceDateText = "31-08-2012";
DateTime sourceDate = DateTime.Parse(sourceDateText, "dd-MM-yyyy")
string formatted = sourceDate.ToString("yyyy-MM-dd");

You can write your possible date formats in array and parse date as following:
public static void Main(string[] args)
{
string dd = "12/31/2015"; //or 31/12/2015
DateTime startDate;
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
"dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy", "MM/dd/yyyy"};
DateTime.TryParseExact(dd, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate);
Console.WriteLine(startDate.ToString("yyyy-MM-dd"));
}

You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:
string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Here, SourceDate is variable in which you will get selected date.

You will need to parse the input to a DateTime object and then convert it to any text format you want.
If you are not sure what format you will get, you can restrict the user to a fixed format by using validation or datetimePicker, or some other component.

This is your primary problem:
The source date could be anything like dd-mm-yyyy, dd/mm/yyyy,
mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.
If you're given 01/02/2013, is it Jan 2 or Feb 1? You should solve this problem first and parsing the input will be much easier.
I suggest you take a step back and explore what you are trying to solve in more detail.

Try this code:
lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");

if (DateTime.TryParse(datetoparser, out dateValue))
{
string formatedDate = dateValue.ToString("yyyy-MM-dd");
}

string sourceDate = "15/06/2021T00.00.00";
DateTime Date = DateTime.Parse(sourceDate)
string date = Date.ToString("yyyy-MM-dd");

Convert.toDateTime(sourceDate).toString("yyyy-MM-dd");

Convert.ToDateTime((string)item["LeaveFromDate"]).ToString("dd/MM/yyyy")
This might be helpful

Related

c# convert yyyymmdd text to dd/MM/yyyy

I have some text in rows as yyyymmdd (eg: 20181211) which I need to convert to dd/MM/yyyy
I am using:
cashRow["BusinessDate"] = Convert.ToDateTime(row.Cells[ClosingDate.Index].Value.ToString()).ToString("dd/MM/yyyy");
I get the error "string was not recognized as a valid DateTime.
Any ideas where I am going wrong?
You'll need to use ParseExact (or TryParseExact) to parse the date:
var date = "20181217";
var parsedDate = DateTime.ParseExact(date, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var formattedDate = parsedDate.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Here we tell ParseExact to expect our date in yyyyMMdd format, and then we tell it to format the parsed date in dd/MM/yyyy format.
Applying it to your code:
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
You have to use ParseExact to convert your yyyyMMdd string to DateTime as follows and then everything is okay.
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
As you already know the exact format of your input yyyyMMdd (eg: 20181211), just supply it to DateTime.ParseExact() and then call ToString() on the returned DateTime object.
string YourOutput = DateTime.ParseExact(p_dates, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Try this:
cashRow["BusinessDate"] = row.Cells[ClosingDate.Index].Value.ToString("dd/MM/yyyy");

DateTime format conversion mm/dd/yyyy to yyyy/mm/dd

Can someone please let me know how do I convert this datetime format into yyyyMMdd
2/28/2017 12:02:04 AM
At the output I should get 20170228
Any advice on this?
If you already have the DateTime as an object
string formattedDate = date.ToString("yyyyMMdd");
If you need to parse the value first.
string dateValue = "2/28/2017 12:02:04 AM";
string format = "M/d/yyyy hh:mm:ss tt";
DateTime dateTime = DateTime.ParseExact(dateValue, format,
System.Globalization.CultureInfo.InvariantCulture);
For reference you can find a breakdown of the Custom Date and Time Format Strings
You need to specify the format of the date.
If you want it for the current time you can try like this :
string dtime = DateTime.Now.ToString("yyyy/MM/dd");
This is the solution I have come up with for you:
string format = "M/d/yyyy hh:mm:ss tt";
string dateString = "2/28/2017 12:02:04 AM";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(dateString, format, provider);
string output = date.ToString("yyyyMMdd");
If you're using C# 6 or later (VS2015), you can format DateTime objects easily by using string interpolation using a custom format string. The custom format string that you're looking for is "yyyyMMdd".
// create your preferred date and time in a new DateTime struct
DateTime yourDateTime = new DateTime(2017, 2, 28, 0, 2, 4);
// format yourDateTime as a string
string yourFormattedDateTime = $"{yourDateTime:yyyyMMdd}";
You can read more about interpolated strings at https://msdn.microsoft.com/en-us/library/dn961160.aspx, and, as previously mentioned by #Adam Carr, you can find more information on custom date and time format strings at https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Getting an error while converting string to DateTime

I am trying to convert a string value into DateTime. It gives me an error as, specified string is not in correct format.
Here is the code,
DateTime myDate = DateTime.ParseExact("07-09-2013 01:14:14:1414", "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
string strDate = "07/09/2013 01:04:02:4";
Convert.ToDateTime(strDate);
DateTime dt = DateTime.Parse(strDate);
Please help in converting the same.
Thanks
Your format seems to be incorrect. Should be:
"dd-MM-yyyy HH:mm:ss:ffff"
Update. If number of digits representing fractions of a second varies, than the best bet is
"dd-MM-yyyy HH:mm:ss:FFFFFFF"
Refer to MSDN for other options for custom time and date formats.
Try in your page_load event:
Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo("tr-TR")
Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("tr-TR")
First, you mixed you years place
07-09-2013 is dd-MM-yyyy format
second, you need a :ffff after seconds
So the final line should be
DateTime myDate = DateTime.ParseExact("2013-07-09 01:14:14:1414", "yyyy-MM-dd HH:mm:ss:ffff", System.Globalization.CultureInfo.InvariantCulture);
Your format isn't correct:
"07-09-2013 01:14:14:1414"
"yyyy-MM-dd HH:mm:ss"
Atleast your date is the other way around, and the milliseconds is not specified.
Correct you format according to this: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
For the downvoter:
The correct format is specified by Andrei: "dd-MM-yyyy HH:mm:ss:ffff"
First of all, you should change your date format to dd-MM-yyyy because it fits with your date format.
Second of all, for miliseconds part, you can use . instead of :
DateTime myDate = DateTime.ParseExact("07-09-2013 01:14:14.1414", "dd-MM-yyyy HH:mm:ss.ffff", System.Globalization.CultureInfo.InvariantCulture);
string strDate = "07/09/2013 01:04:02.4";
Convert.ToDateTime(strDate);
DateTime dt = DateTime.Parse(strDate);
Here a DEMO.
For more information, check Custom Date and Time Format Strings

C# string to SqlDateTime: how to set format for recognition?

I need to use
SqlDateTime.Parse(val)
where val is a string such as " 23.3.1992 00:00:00 ".
The string is in European format, that is, day precedes month. However Parse wants "American" format. How I can tell it to use particular datetime format / locale?
Thanks in advance!
Try this:
string val = "23.12.1992 00:00:00";
// Parse exactly from your input string to the native date format.
DateTime dt = DateTime.ParseExact(val, "dd.M.yyyy hh:mm:ss", null);
// Part to SqlDateTime then
System.Data.SqlTypes.SqlDateTime dtSql = System.Data.SqlTypes.SqlDateTime.Parse(dt.ToString("yyyy/MM/dd"));
This could be done in one statement, but just separated for illustration.
Have you tried DateTime instead of SQLDateTime
DateTime d = DateTime.Parse(val);
String s = d.ToString(CultureInfo.CreateSpecificCulture("en-US"));
Can you try this ?
string valInEuropean = "23.3.1992 00:00:00";
DateTime dateInEuropean = DateTime.Parse(valInEuropean);
string valInAmerican = dateInEuropean.ToString("yyyy-MM-dd HH:mm:ww");
For converting a string to datetime object when the format is known(in this case )
use
DateTime dwweek = DateTime.ParseExact("23.3.1992 00:00:00", "dd.MM.yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

String not getting converted to datetime

I have I have Excel file from where I am getting date in string format as "30-12-1899 07:50:00:AM"
When I am trying to convert it to DATETIME then it is giving error as
String was not recognized as a valid DateTime
I am trying to convert it like this
Convert.ToDateTime(homeToSchool[7],new DateTimeFormatInfo { ShortDatePattern = "dd-MM-yyyy", DateSeparator = "-" })
Use DateTime.ParseExact
string myDate = "30-12-1899 07:50:00:AM";
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy hh:mm:ss:tt",
CultureInfo.InvariantCulture)
For more information about Date and Time Format Strings,
Custom Date and Time Format Strings
Since you are reading this from excel I hope this would help
DateTime.FromOADate(homeToSchool[7].ToString("dd-MMM-yyyy");

Categories

Resources