convert string to date(dd/MM/yyyyy) format in c# - c#

i have a query string with format MM/DD/YYYY
I am using it in c# like
DateTime d = Request.QueryString["dateTime"].toString();
its giving me a lot of error saying the date time format is not recognized. If i manually change the datetime in browser address bar (query string) to dd/mm/yyyy then the program just works fine.
I cannot change the query string, is there a way in c# to get it from browser and then convert into date like dd/mm/yyyy please?
edit:
the query string:
http://localhost:49543/HM/Admin/ViewDetails.aspx?OrderNo=10&DateCreated=08/30/2010
so you can see the datecreated part is in MM/DD/YYYY format.
I am not able to grab it from c#. If I manually change that to 30/08/2010, it works

DateTime d = DateTime.ParseExact(Request.QueryString["dateTime"], "dd/MM/yyyy", CultureInfo.InvariantCulture);

How to turn string from request into DateTime:
DateTime d = DateTime.ParseExact(Request.QueryString["dateTime"], "dd/MM/yyyy", null);

DateTime.ParseExact is the solution you seek for.
But I recommend you to validate the querystring data with a function as follows:
bool isValidDate(string dtStr) {
string pattern = #"^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$)";
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(pattern);
return re.IsMatch(dtStr);
}
EDIT 1: Besides ParseExact, you can use the following:
DateTime.Parse(dateString, new System.Globalization.CultureInfo("tr-TR"))
Turkish datetime format is dd/MM/YYYY.

// Parsing:
DateTime d = DateTime.Parse(Request.QueryString["dateTime"].toString());
// Conversion:
string dString = d.ToWhateverFormatYouWant();
And here's some info on formatting dates:
http://msdn.microsoft.com/en-us/library/az4se3k1(VS.71).aspx

DateTime.TryParse could be a great option..

Try this it should work
DateTime d =
DateTime.ParseExact(Request.QueryString["dateTime"],
"dd'/'MM'/'yyyy",
CultureInfo.InvariantCulture);
I faced something similar: DateTime Format in C#

You can use: DateTime.Now.ToString("dd/MM/yyyy");

Related

Formatting Date time to Specific Format

I am trying to convert the DateTime to following Format.
2015-06-11 07:14:03.930
I have tried with ,
string plannedStartTime = startTime.ToString("o");
output:2015-06-12T16:54:47.3206929+05:30
and
string plannedStartTime = startTime.ToString("u");
output:2015-06-12 16:56:57Z
Not getting any formatters from MSDN
Any other Formatters?
all you need is a right format string
try using this startTime.ToString("yyyy-MM-dd HH:mm:ss.fff")
There is no standard date and time format for your output. You need to use custom date and time format specifiers with a culture that have : as a TimeSeparator like InvariantCulture;
string plannedStartTime = startTime.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
If your CurrentCulture already have : as a TimeSeparator, you don't need to pass second parameter in ToString method.
Hope this is what your asking for
string plannedStartTime = startTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

C# - How to convert string date to DateTime format

I have a string date
"7.08.2014"
and want to convert into this format :
2014-07-08
I tried a no of solution that previously propoed on stackoverflow, unfortunately none of work for me. Any suggestion please, here is my code
var parsedDate = DateTime.ParseExact(match.date, "MM/dd/yyyy", CultureInfo.InvariantCulture);
It keep throws an error
Additional information: String was not recognized as a valid DateTime.
You're using the wrong format. Try this:
var parsedDate = DateTime.ParseExact(match.date, "d.MM.yyyy", CultureInfo.InvariantCulture);
DateTime.ParseExact attempts to convert a string representation of a datetime to a DateTime by using the format provided in the second parameter.
To obtain a string in the other format you have to call ToString on parsedDate with a custom format specifier:
var dateInCustomFormat = parsedDate.ToString("yyyy-dd-MM", CultureInfo.InvariantCulture);

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

DateTime Conversion and Parsing DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")

I store some DateTime in a CSV log with:
DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")
When I try to read it I found something like:
"05/15/2012 10:09:28.650"
The problem is when I try to cast it as a DateTime again...
DateTime.Parse("05/15/2012 10:09:28.650");
Throws an Exception "Invalid DateTime" or something like that...
How can I properly re-read the DateTime?
You can use DateTime.ParseExact:
string format = "MM/dd/yyyy hh:mm:ss.fff";
DateTime d = DateTime.ParseExact("05/15/2012 10:09:28.650",
format,
System.Globalization.CultureInfo.InvariantCulture);
Standard Date and Time Format Strings
use DateTime.ParseExact with specifying the format
String dateStr=DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff");
DateTime date = DateTime.ParseExact(dateStr,"MM/dd/yyyy hh:mm:ss.fff",System.Globalization.CultureInfo.InvariantCulture);
You should use this method to parse your string. You would have to make a class, imlementing IFormatProvider, but if you want to use a custom DateTime format, it's the best method I can think of.

String was not recognized as a valid DateTime " format dd/MM/yyyy"

I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message

Categories

Resources