Parse a string to a date without slashes - c#

In C# / Winform, I'm able to parse a string to a date if the user input: dd/mm/yyyy
DateTime.Parse(date).ToString();
I would like to be able to parse without the slash (like in a datagridview or a DateTimePicker for example).
01022012 should be parsed to 01/02/2012
Anyone know how to parse it with DateTime.Parse?
Here is my code :
private void dataGridView_BadgeService_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateDebut" || dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateFin")
{
string date = Convert.ToString(e.FormattedValue).Trim();
if (date.Length > 0)
{
try
{
DateTime _date;
DateTime.TryParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _date);
date = _date.ToShortDateString();
dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = date;
}
catch
{
MessageBox.Show("Merci de saisir une date, ou laissez cette zone vierge", "Action-Informatique", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
e.Cancel = true;
}
}
}
}
Here is the Exception Message :
It says that : "System.FormatException: The string is not recognized as a DateTime valide"

Try with something like this...
string unslashedValue = "01022012"
DateTime date;
DateTime.TryParseExact(unslashedValue, "ddMMyyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, date);
... and, with date variable, you only need to...
string slashedValue = date.ToString("dd/MM/yyyy");

HuorSwords isn't wrong (other than the use of string as the input value), but the answer doesn't strictly answer the question: in order to display the date as requested, you need to format to a string after the fact:
DateTime date = DateTime.ParseExact(input,
"ddMMyyyy", CultureInfo.InvariantCulture);
string formattedDate = date.ToString("dd/MM/yyyy");

That seems like an awful lot of work when you could do something as simple as the two examples below. Date and time can be formatted using predefined formats and also user-defined formats.
This is a link to a brief video demonstrating both uses from a text editing program I'm designing.
https://od.lk/s/MTRfMjY2NzQxODVf/2022-03-20-20-55-52.mp4
This link will certainly get you on the right track:
https://www.vbtutor.net/vb2008/vb2008_lesson16.html
'Declaration (If you wish to use SpeechSynthesizer)
Private Ethro As SpeechSynthesizer = New SpeechSynthesizer()
Ethro.SpeakAsync(Format(Now, "Long Date"))
'Or a simple MsgBox:
MsgBox(Format(Now, "Long Date"))

Related

Converting string dd/mm to datetime

Converting a String to DateTime
As the above link says I can do conversion if I'm having a the complete dd/mm/yyyy,But I'm having only dd/mm not the year field.
I have achieve it by changing the date to mm/dd format and using Convert.ToDateTime(date).So any help please.
You can parse that string. Just remember that the Month part is MM not mm (minutes)
string data = "01/01";
DateTime dt;
DateTime.TryParseExact(data, "dd/MM", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt);
Console.WriteLine(dt.ToLongDateString());
Of course the missing year is assumed to be the current year
You can use this source to learn more about specifiers for parsing custom date's.
Put your string variable instead of CustomDate field.
DateTime d = DateTime.ParseExact(CustomDate, "dd/MM",System.Globalization.CultureInfo.CurrentCulture);
I would use the function DateTime.TryParseExact since you can use it within an If - else structure very easily
private DateTime date;
private myString = "23/04";
if (DateTime.TryParseExact(myString, "dd/MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
myDate = date;
}
else
{
//do nothing
}
With this you can catch errors when parsing the string.

How to parse the date time string including the milliseconds using c#?

I am trying to convert a datatime string "including milliseconds" into a DataTime. I tried tried to use DateTime.TryParseExact but it does not give me a milliseconds.
Here is what I have tired
public static DateTime? dateTimeVal(string raw, string format = null)
{
DateTime final;
if(raw != null){
if( format != null){
string[] formats = new[] { format };
if (DateTime.TryParseExact(raw, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out final))
{
return final;
}
}
if (DateTime.TryParse(raw, out final))
{
return final;
}
}
return null;
}
This is how I use the method above
DateTime? dt = dateTimeVal("2016-03-14 11:22:21.352", "yyyy-MM-dd HH:mm:ss.fff");
However, dt gives me this 3/14/2016 11:22:21 AM
How can I get the value to include the milliseconds?
DateTime final = new DateTime();
var test = DateTime.TryParseExact("2016-03-14 11:22:21.352", new string[] { "yyyy-MM-dd HH:mm:ss.fff" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
This works for me.
Just take care for your fff. If you write them uppercase, the milliseconds will be supressed. Lowercase they will be parsed.
The only thing away from that I can imagine is you have used .ToString without providing any format. Then you'll get:
Are you sure you've written the providing format lowercase inside your code? Also have you used .ToString() with an output-format that shows up the milliseconds?
If you want to get the DateTime as string with milisecond, then you can use the following code;
string dateTime = dt.Value.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Hope this helps.

CONVERT date format from mm-dd-yyyy to dd-mmm-yyyy in c#

I am trying insert asp.net form field values to oracle database table. I have a date field which is in "MM-DD-YYYY" format. I need to add that date to oracle table. So i am trying to convert that date format to "DD-MMM-YYYY" format. But i am getting the following error.
code:
var creation_date = DateTime.ParseExact(CreationDateTextBox.Text, "DD-MMM-YYYY",null);
Text box value is: 12-12-2013.(No time)
i am getting error like "String was not recognized as a valid DateTime".
You need to parse the date using MM-dd-yyyy but then you shouldn't need to format it at all. Just pass it to the database as a DateTime using parameterized SQL.
DateTime creationDate;
if (DateTime.TryParseExact(CreationDateTextBox.Text, "MM-dd-yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out creationDate))
{
// Use creationDate within a database command, but *don't* convert it
// back to a string.
}
else
{
// Handle invalid input
}
Avoid string conversions wherever you can. Indeed, ideally use a date/time picker of some description rather than just a text field - that will give users a better experience and reduce the risk of poor conversions.
Also note that whenever you want to use custom string conversions (parsing or formatting) you should read the MSDN docs - YYYY and DD aren't valid format specifiers.
This might help :)
String myString = "12-30-2014"; // get value from text field
DateTime myDateTime = new DateTime();
myDateTime = DateTime.ParseExact(myString, "MM-dd-yyyy",null);
String myString_new = myDateTime.ToString("dd-MM-yyyy"); // add myString_new to oracle
Try this
DateTime dt = Convert.ToDateTime(CreationDateTextBox.Text);
var creation_date=String.Format("{0:dd-MMM-yyyy}", dt)
OR try as
dt.ToString("dd MMM yyyy");
You have three M for the month, which is used for month names. Just use two M.
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;
}

DateTime Format Handling

I have a program that has synchronization. That means I need to save the last synchronization date and check if it needs to be synchronized.
So, I have this:
IS.SaveContactsRetrieveDate(DateTime.Now.ToString("dd.MM.yyyy"));
Saving a date to Isolated Storage.
Then, when I call IF:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
if (contactsRetriveDate == "" || DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate)) == 1)
{
MessageBox.SHow("");
}
The problem is that when user changes the region code fails here:
DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate))
With incorrect input error.
I understand that Latvian format is dd.MM.yyyy and USA MM/dd/yyyy - but I can't find a solution...
I need all datetime parsed in one format, so I could add days, weeks and compare date.
You should serialize and deserialize your date in a culture-independent manner (where "d" is the "Short date pattern" of the Standard Date and Time Format Strings):
var s = DateTime.Now.ToString("d", CultureInfo.InvariantCulture);
var d = DateTime.Parse(s, CultureInfo.InvariantCulture);
You can use ParseExact
DateTime.ParseExact(datestring, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
you already know format so you can go for this, but make sure the string is in same format and never changes.
u can try this one:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
DateTime contactsRetriveDat = Convert.ToDateTime(contactsRetriveDate);
if (contactsRetriveDate == "" || toDate.CompareTo(contactsRetriveDat)==0)
{
MessageBox.SHow("");
}

.net DateTime formatting hide time if midnight?

I'm working on formatting datetime's to display on a graph, and its working great so far. I have the format string:
M/dd/yyyy HH:mm:ss
and it prints as I'd like it to except the following: I want to completely hide the HH:mm:ss if the time is midnight.
Is it possible to do without a custom iformatprovider?
Thanks!
DateTime time = DateTime.Now;
string txt = time.ToString(time == time.Date ? "M/dd/yyyy" : "M/dd/yyyy HH:mm:ss");
DateTime time = DateTime.Now;
string format = "";
if (time.Hour == 0)
{
format = "M/dd/yyyy";
}
else
{
format = "M/dd/yyyy HH:mm:ss";
}
A culture-independent version of the solution proposed by #JDunkerley would be:
DateTime time = DateTime.Now;
string txt = time.ToString(time == time.Date ? "d" : "g");
More about standard date and time format strings here.
The proposed solution is not a very good one because it does not take into account user's localized time format, and simply assumes US English.
Here's how it should've been done:
public static string formatDateTimeWithTimeIfNotMidnight(DateTime dt)
{
//RETURN:
// = String for 'dt' that will have time only if it's not midnight
if (dt != dt.Date)
{
//Use time
return dt.ToString();
}
else
{
//Only date
return dt.ToShortDateString();
}
}

Categories