string to MM/dd/yyyy - c#

I have a string like this:
3/4/2013 or like this 11/10/2012. This is in mm/dd/yyyy format which I want to convert to MM/dd/yyy. I am doing like this:
DateTime publicationDate = DateTime.ParseExact(myDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
This is throwing me an error:
String was not recognized as a valid DateTime.
What is going on here?
EDIT:
After reviewing all the answers, I want to show Month and Day of the DateTime variable.
So I cannot do something like this:
string publicationDate = DateTime.ParseExact(myDate, "M/d/yyyy", CultureInfo.InvariantCulture).ToString("MM/dd/yyyy");
Having a string will not solve my problem because I am using this variable to show only day and month.
When I tried parsing this 'publicationDate' back to DateTime is truncates the '0's from month and day.
Hope I made my point here.
Answered:
string publicationDate = DateTime.ParseExact(myDate, "M/d/yyyy", CultureInfo.InvariantCulture).ToString("MM/dd");

You should add leading zeroes to the month and day.
This way: 04/03/2013
var myDateTime = DateTime.ParseExact(
"03/04/2013",
"MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
If leading zeroes are a problem, then do:
var myDateTime = DateTime.ParseExact(
"3/4/2013",
"M/d/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
Finally, if you want to add leading zeroes:
string myFormattedDateTime = DateTime.ParseExact(
"3/4/2013",
"M/d/yyyy",
System.Globalization.CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy");

Use this pattern instead: "M/d/yyyy" to parse it and "MM/dd/yyyy" for ToString:
DateTime publicationDate = DateTime.ParseExact(dt, "M/d/yyyy", CultureInfo.InvariantCulture);
// if you want to display two digits for day and month:
Console.WriteLine(publicationDate.ToString("MM/dd/yyyy"));
It works for both as you can see here: http://ideone.com/M7luBD

Simple solution was this:
string publicationDate = DateTime.ParseExact(myDate, "M/d/yyyy", CultureInfo.InvariantCulture).ToString("MM/dd");
Thank you all for your answers!

Convert your string ToDateTime first. Make sure you have leading zeroes.
string date = "03/04/2013";
DateTime dt = Convert.ToDateTime(date);

[TestCase("3/4/2013", 3, 4, 2013)]
[TestCase("11/4/2013", 11, 4, 2013)]
public void DateTest(string date, int month, int day, int year)
{
var publicationDate = DateTime.ParseExact(date, "M/d/yyyy", CultureInfo.InvariantCulture);
Assert.AreEqual(day, publicationDate.Day);
Assert.AreEqual(month, publicationDate.Month);
Assert.AreEqual(year, publicationDate.Year);
}
Both test cases pass.
If your format asks for MM/dd/yyyy then you need to supply the string as such (04/03/2013 instead of 4/3/2013). So either
use M/d/yyyy if your supplied date is without leading zero's
or use the MM/dd/yyyy if you can supply leading zero's

Related

String was not recognized as a valid DateTime

I have a string 2016. I am wondering how can I parse this string to a date time?
I have tried Datetime.ParseExact but it said it is not a valid format
string period = "2016"
DateTime date = DateTime.ParseExact(period, "YYYY", CultureInfo.InvariantCulture);
Help will be appreciated. Thanks
use "yyyy" instead for YYYY then you will get the expected answer;
string period = "2016";
DateTime date = DateTime.ParseExact(period, "yyyy", CultureInfo.InvariantCulture);
You can check More DateTime Formats here

Read Date Value from TextBox and Convert to Month and Year

i have a text-box in a detailview and the value of the text-box is a Date but it only shows the Month and Year and it is like this:November 2013 so i want to take this value and convert like this: 20131101. So as you can see, i would like the format to be YYYYMMDD but the day should always be 01 which is the first of the month. So how can i go from this November 2013 to this 20131101? here is my code and i know i have to convert from string to date first:
string myDate = ((TextBox)DetailView1.FindControl("InputDate")).Text.ToString();
Convert it:
TextBox txtInputDate = (TextBox)DetailView1.FindControl("InputDate");
DateTime dt = DateTime.ParseExact(txtInputDate.Text, "MMMM yyyy", CultureInfo.InvariantCulture);
then convert it to string again:
txtInputDate.Text = dt.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
C# is pretty good at parsing stringy dates, you could lean on the build it parsing:
string myDateString = ((TextBox)DetailView1.FindControl("InputDate")).Text.ToString();
DateTime myDate;
if (DateTime.TryParse(myDateString, out myDate)) {
// myDate now contains a proper .NET date.
}
Now you have a proper DateTime, you can output it in any format you like.
DateTime test = DateTime.Parse("November 2013");
Console.WriteLine(test.ToString("yyyyMMdd"));
Use the DateTime.ParseExact() method, like this:
var theParsedDate = DateTime.ParseExact(myDate, "MMMM yyyy",
CultureInfo.InvariantCulture);
Now you can use the parsed date however you wish, convert it to string, send it to database, etc.

Parsing datetime of the format "2013-Jan-31" throws error

I have a datetime column in database.
DateTime end_date = DateTime.ParseExact("2013-Jan-31", "yyyy-MM-dd", CultureInfo.InvariantCulture);
Why isn't this working?
This is not working because MM would mean January to be 01. If this is the format of the date you're trying to parse, try the format "yyyy-MMM-dd".
Hope this helps
Try like this;
DateTime a = DateTime.ParseExact("2013-Jan-31", "yyyy-MMM-dd", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine (a);
Output:
31.01.2013
Look at from MSDN Custom Date and Time Format Strings
To use such a name of the month you need to take "MMM" so it will be
myObject.end_date = DateTime.ParseExact("2013-Jan-31", "yyyy-MMM-dd", System.Globalization.CultureInfo.InvariantCulture);
MM represents a two-digit numerical month (such as "01").
MMM represents the abbreviated month (such as "Jan").
Which means that you need
myObject.end_date = DateTime.ParseExact("2013-Jan-31", "yyyy-MMM-dd", System.Globalization.CultureInfo.InvariantCulture);
See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx for a list of string format specifiers.

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

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

Parse C# string to DateTime

I have a string like this:
250920111414
I want to create a DateTime object from that string. As of now, I use substring and do it like this:
string date = 250920111414;
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);
Is it possible to use string format, to do the same, without substring?
Absolutely. Guessing the format from your string, you can use ParseExact
string format = "ddMMyyyyHHmm";
DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
or TryParseExact:
DateTime dt;
bool success = DateTime.TryParseExact(value, format,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.
EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.
You could use:
DateTime dt = DateTime.ParseExact(
date,
"ddMMyyyyHHmm",
CultureInfo.InvariantCulture);
string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
DateTime Formats

Categories

Resources