when i am trying to connect c# code to mysql database there is a mistake in date datatype
try
{
CultureInfo CultureInfoDateCulture = new CultureInfo("ja-JP");
DateTime d = DateTime.ParseExact(accountend, "yyyy/MM/dd", CultureInfoDateCulture);
return true;
}
catch
{
return false;
}
when i have to collect date from the month calender i have used this validation for MYSQL and the datatype i have used is DATE datatpe
I have been getting the folllowing error
String was not recognised as a valid date time
please help me guys.... Thanks in advance
MYSQL Date Format is yyyy-MM-dd so you should use the same format while parsing it in the DateTime.ParseExact() method.
Try This:
DateTime d = DateTime.ParseExact(accountend, "yyyy-MM-dd",
CultureInfoDateCulture);
EDIT : From Your Comments your Date Format is M/d/yyyy
Try This:
DateTime d = DateTime.ParseExact(accountend, "M/d/yyyy",
CultureInfoDateCulture);
DateTime.ParseExact requires that the format string represent accurately the day, month and year of the string that need to be converted
So assuming that your date string is 4/11/2014 (day, month, year) you need
try
{
CultureInfo CultureInfoDateCulture = new CultureInfo("ja-JP");
DateTime d = DateTime.ParseExact(accountend, "d/M/yyyy", CultureInfoDateCulture);
return true;
}
catch
{
return false;
}
instead if the format is month, day, year, the format string is
DateTime d = DateTime.ParseExact(accountend, "M/d/yyyy", CultureInfoDateCulture);
By the way, your date is in the format expected by the InvariantCulture, so you could avoid the creation of the CultureInfo in this context, it is enough to use
DateTime d = DateTime.Parse(accountend, CultureInfo.InvariantCulture);
Related
I have a datetime value in a CSV file and below is the sample data:
20/06/2016 11:52
21/06/2016 11:52
22/06/2016 11:52
Non when I try to parse this datetime, I get error:
String was not recognized as a valid DateTime.
I am not sure what will be the format of this date but I would always like to parse it in that culture in which my application will be using. So based on current culture I would like to parse my date.
This is how I am trying but getting error as above:
string row = "20/06/2016 11:52"
Try 1:
CultureInfo culture = CultureInfo.CurrentCulture;
DateTimeStyles styles = DateTimeStyles.None;
DateTime dateValue;
DateTime.TryParse(rowValue, culture, styles, out dateValue); // {1/1/0001 12:00:00 AM}
Try 2
DateTimeFormatInfo usDtfi = new CultureInfo(culture.Name, false).DateTimeFormat;
var l = Convert.ToDateTime(rowValue, usDtfi); //String was not recognized as a valid DateTime
var g = DateTime.Parse(rowValue, usDtfi);//String was not recognized as a valid DateTime
All this above approches are failing and I would like to have exact date and want to store in my SQL Server database table.
My system datetime is in format : mm/dd/yy
I have already seen some questions like below:
String was not recognized as a valid DateTime " format dd/MM/yyyy"
Datetime format Issue: String was not recognized as a valid DateTime
But all those answers are specifying date format but I don't know what will be the format; that is why I am trying to detect from current culture. I am not sure whether I am thinking in a right way.
If you're sure that each string you encounter will be in a proper format, but you just don't know which one, one thing you can do is get an array of all the different formats on your machine and use that in the parse exact method:
var formats = (from CultureInfo ct in CultureInfo.GetCultures(CultureTypes.AllCultures)
select ct.DateTimeFormat.GetAllDateTimePatterns()).SelectMany((x) => x).ToArray();
DateTime test = DateTime.ParseExact("20/06/2016 11:52", formats, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
That code on my machine generates over 26,000 formats. As long the string follows one of them it will be accepted.
If getting the proper format will be inconsistent you could go this route:
var formats = (from CultureInfo ct in CultureInfo.GetCultures(CultureTypes.AllCultures)
select ct.DateTimeFormat);
string dateString = "20/06/2016 11:52";
DateTime temp = new DateTime(0);
foreach (DateTimeFormatInfo dfi in formats)
{
if (DateTime.TryParseExact(dateString, dfi.GetAllDateTimePatterns(), dfi, DateTimeStyles.None, out temp))
{
break;
}
}
if(temp == new DateTime(0))
{
//save string to get it's format
}
If you are 100% sure the format will always be the same, you can use the method ParseExact like:
var parsedDate = DateTime.ParseExact(row, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);
I have the Date and Time like this 2016/11/28 and time 07:30 PM. And combine this string and make like below
string mydate = extras.GetString("Apodate") + " " + extras.GetString("Apostarttime");
so mydate string contain 2016/11/28 07:30PM.
No I want to convert this string to below format
"yyyy-MM-dd'T'HH:mm:ss'Z'"
So I try this way:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
try
{
Java.Util.Date startdate = dateFormat.Parse(mydate);
Java.Util.Date enddate = dateFormat.Parse(mydate1);
SimpleDateFormat rformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime dt1 = DateTime.ParseExact(rformat.Format(startdate).ToString(), "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
model.StartTime = dt1;
}
catch (ParseException e)
{
e.PrintStackTrace();
}
But my model.StartTime contain 12/11/0195 7:30:00 PM. But I want
2016/11/28 7:30:00 PM. as a DateTime.
First the thing you should consider to do is
1. Convert String(type) To DateTime(type)
- Search how parseExact do first, I think "yyyy-MM-dd'T'HH:mm:ss'Z'" is not the correct datetime format
2. When you got Datetime(type) you can display to any string format you want
- Search how to convert type DateTime to string
Link
https://stackoverflow.com/questions/5366285/parse-string-to-datetime-in-c-sharp#=
How do I get the AM/PM value from a DateTime?
TLDR;
SimpleDateFormat rformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");//Format text as what ParseExact method can do
DateTime dt1 = DateTime.ParseExact(rformat.Format(startdate).ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);//plz become Datetime!!! And don't give me a runtime error here
model.StartTime = dt1;
And when you want to display model.StartTime
string Datetxt = model.StartTime.ToString("yyyy/MM/dd'T'HH:mm tt'Z'", CultureInfo.InstalledUICulture) //now become a beautiful string with unwanted chars 'T' and 'Z'
I'm trying to parse a date string in mm/dd/yyyy to date type, but it triggers an error saying:
String was not recognized as a valid DateTime.
This is the code I'm using:
Dim mydate As Date
If filter = 4 Then
mydate = Date.ParseExact(datepart, "mm/dd/yy", System.Globalization.DateTimeFormatInfo.InvariantInfo)
End If
I don't understand what I did wrong, any help is appreciated.
You have two little errors in your format string:
DateTime mydate = DateTime.ParseExact("07/27/2016",
"MM/dd/yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo);
Months are parsed by "MM" not "mm" (lower case is for minutes)
The four digit year is parsed by "yyyy" not "yy"
Your date format is wrong, use MM/dd/yyyy instead mm/dd/yy try below
Date.ParseExact(datepart, "MM/dd/yyyy", CultureInfo.InvariantCulture)
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date-only value with invariant culture.
string dateString = "06/15/2008";
string format = "d";
var result = DateTime.ParseExact(dateString, format, provider);
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
In earlier vb.net 2008 I used the DateTime to read the date in dd/mm/yy format.
I use to change the culture info to UK format. So that the date will be selected from SQL server as in dd/mm/yy format.
But I know it's not good to play with CultureInfo. Even though I used like the following manner.
Any other better Ideas for me?
Sub Form_Load()
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-GB", False)
End Sub
Any other better Ideas for me? Thanks for the Ideas.
Thanks & Regards.
From DateTime to string:
string s = DateTime.Today.ToString("dd/MM/yyyy");
From string to DateTime:
DateTime d;
bool success = DateTime.TryParseExact("26/05/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
In C# you could get the date string in desired format like,
string date = DateTime.Now.ToString("dd/MM/yyyy");
If you want to get DateTime object from string value representing DateTime in specific culture, you can do
DateTime dt = new DateTime();
DateTime.TryParse("16/01/2011", System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"),
System.Globalization.DateTimeStyles.None, out dt);
DateTime --> String
DateTime.Now.ToString( new CultureInfo("fr-FR", false) );
String --> DateTime:
The preferred method would probably be DateTime.Parse()
dateString = "16/02/2008 12:15:12";
try
{
dateValue = DateTime.Parse(dateString, new CultureInfo("en-GB", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
This way you are not changing the Culture info of the current Context. This does assume you know what the format will be beforehand though.
You can format the date using the CultureInfo, without setting the culture for the whole thread, thanks to the IFormatProvider interface:
DateTime d = DateTime.Now;
CultureInfo c = new CultureInfo("en-GB", false);
string s = d.ToString(c.DateTimeFormat);
This has the added advantage that you don't have any hard-coded formats, and if the user changes the localisation settings on their machine, your application will reflect their preferences.
You can use DateTime.TryParse to parse the date...
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}
And even use an IFormatProvider to help TryParse work out the format.
CultureInfo c = new CultureInfo("en-GB", false);
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, c.DateTimeFormat, DateTimeStyles.None, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}