DateTime.ToString from all formats to dd/MM/YYYY? - c#

I have a simple routine which parses a DateTime.Now & performs a .ToString() on it to add it into a file name to be saved:
DateTime timeNow = DateTime.Now;
string dateNow = timeNow.ToShortDateString();
DateTime dateTime = DateTime.ParseExact(dateNow, "dd/MM/yyyy", CultureInfo.InvariantCulture);
string DateString = dateTime.ToString("dd-MMM-yy");
string fileName = string.Concat("MyArticle_" + region + "_" + DateString + fileExtension);
this is the resulting output string:
MyArticle_Africa_07-May-15.PNG
This is all good until I get a user on an American machine where the DateTime settings are different e.g.
05-07-15
In this case my ParseExact() method throws an exception as the input is not a valid date time. Is there a way to accommodate all date time inputs & parse to dd/MM/YYYY?

Actually, you don't need all these lines of code. You just need this:
// We just have to pass to the ToString
// method the exact format we want. Under the hood the CLR has
// the know how to execute this command and you get the desired
// output.
string DateString = DateTime.Now.ToString("dd-MMM-yy");
Furthermore, we use the DateTime.ParseExact method, when we want to get this exception you have mentioned. Saying this, I mean that we know that the string representation of dates, which we want to parse are of the exact format, we have specified in DateTime.ParseExact and if some of them aren't we wan't to be informed know it. Usually, we would have a try catch clause and in the catch clause we log this.

You need to try this:
string DateString = DateTime.Now.ToString("dd-MMM-yy");
string fileName = String.Concat("MyArticle_" + region + "_" + DateString + fileExtension);

You don't even need to convert DateTime.Now to a string, you can create the entire string in one step using String.Format :
var fileName = String.Format("MyArticle_{0}_{1:dd-MMM-yy}{2}",
region,DateTime.Now,fileExtension);
or
var fileName = String.Format(CurrentInfo.InvariantCulture,
"MyArticle_{0}_{1:dd-MMM-yy}{2}",
region,DateTime.Now,fileExtension);
to avoid internationalization issues.

Related

Error on DateTime.ParseExact

I have a date in an oracle database, that I query on. This date looks like:
5/3/2016 (after I remove the time portion)
I try to convert this date to a DateTime. I am using:
ParseExact(String, String, IFormatProvider)
I am doing something wrong, which I can't figure out.
My code is shown below. Notice that the variable called "res", has the value 5/3/2016 as described above
try {
while(reader.Read()) {
string res = reader[0].ToString().Substring(0, 8);
mailer.SendSmtpMail4dev("Result: " + res);
mailer.SendSmtpMail4dev("Result: " + DateTime.ParseExact(res, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture));
}
} catch(Exception e) { ...
for DateTime.ParseExact The format of the input string and the format string should be the same, so use:
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
In your case the supplied date is 5/3/2016 and you are specifying that the format is "dd-MM-yyyy" such conversions are not possible. if you need to change the format means you can do like the following:
string res = "5/2/2016";
DateTime givenDate = DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string newFormatedDate = givenDate.ToString("dd-MM-yyyy");
Use:
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture);
Refer to the MSDN article for details
Use
DateTime.ParseExact(res, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd-MM-yyyy")
since your res date is dd/MM/yyyy format but you have tried to cast is as dd-MM-yyyy, in DateTime.ParseExact() you have to provide datetime and format string as same format, correct code will be like this
mailer.SendSmtpMail4dev("Result: " + DateTime.ParseExact(res, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd-MM-yyyy"));
If you have a date why do you convert it to String
// What if server's NLS_* settings are changed? What does 8 stand for?
reader[0].ToString().Substring(0, 8);
and then Parse again? If reader[0] is a date use DateTime:
try {
while(reader.Read()) {
// 0th field is date, then treat it as being date
DateTime date = Convert.ToDateTime(reader[0]);
//TODO: put the right formats here
mailer.SendSmtpMail4dev("Result: " + date.ToString("dd-MM-yyyy"));
mailer.SendSmtpMail4dev("Result: " + date.ToString("dd-MM-yyyy"));
}
}
catch(Exception e) {
...
}
The solution to my problem is marked above, but I just want to state something important, so that others might save some time. Some suggested solutions, suggest doing: DateTime.ParseExact(res, "dd/MM/yyyy" ...) which also seems to be in many other examples on the net, so I'm not saying it's wrong. However. This didn't work for me, I spent some time, before I tried doing:
DateTime.ParseExact(res, "d/M/yyyy" ...)
Notice that in the later solution, there is only one d, and one M.
But my main problem, like everyone pointed out, was probably that I was using:
"dd-MM-yyyy" instead of "dd/MM/yyyy" (which is the same format as the oracle value)
Hope this will save you some time

Date time format in C#

I need "24/01/2012" but Why it always returns "24/1/2012"
when I am using this
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}", (SessionHelper.SearchFilingStartDate.Value.Day.ToString() + "/" + SessionHelper.SearchFilingStartDate.Value.Month.ToString() + "/" + SessionHelper.SearchFilingStartDate.Value.Year.ToString()));
Just do with this :
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",SessionHelper.SearchFilingStartDate.Value);
SessionHelper.SearchFilingStartDate.Value seems to be a DateTime value.
Then pass it directly without all that string conversions for day, months and year.
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",
(SessionHelper.SearchFilingStartDate.Value);
The format string "dd/MM/yyyy" contains enough information to allow the Format method to prepare the resulting string directly from your DateTime value
You don't need the String.Format statement. You can do it with the Date's ToString method:
txtFilingStartDate = SessionHelper.SearchFilingStartDate.ToString.Value("dd/MM/yyyy");
There's a lot more information on the MSDN page for Custom Date and Time Format Strings
You are passing a string and the format you specified for it is unrecognized. Assuming that this is a datetime you are passing, don't do all that conversion first:
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}", SessionHelper.SearchFilingStartDate.Value)
When you format a string using a date/time formatting ({0:dd/MM/yyyy}) themethod is expecting an instance of DateTime, you are passing it a string
You probably want simply:
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",SessionHelper.SearchFilingStartDate.Value);

Simplify string splitting

I am getting a result like this "PR242714031213" from a SQL query. This is basically a string PR + ssmmHHddMMyy. I need to extract and format it to a simple date ddMMyyyy.
I am using the following snippet with substrings which is working:
string rawDate = (string)lastProjaddedDate.ExecuteScalar();
string year= rawDate.Substring(12,2);
string month=rawDate.Substring(10,2);
string day=rawDate.Substring(8,2);
string date = day + "/" + month + "/" +"20"+ year;
Label4.Text =date;
I am wondering if I can simplify the code to get the ddMMyyyy out of it.
PS: I know I need to change the way it is codified in the DB to avoid problems in few decades but lets start to simplify it.
You can do:
Step - 1: Strip `PR` from the string
Step - 2: Parse to .Net `DateTime` object
Step - 3: Format to required format
Code :
string rawDate = "PR242714031213";
rawDate = rawDate.Substring(2);
DateTime dt;
if (!DateTime.TryParseExact(rawDate,
"ssmmHHddMMyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//invalid date
}
string formattedDate = dt.ToString("ddMMyyyy");
In one statement it would be:
string formattedDate = DateTime.ParseExact(rawDate.Substring(2),
"ssmmHHddMMyy",
CultureInfo.InvariantCulture)
.ToString("ddMMyyy");
Assuming you update the way dates are stored in the DB all you need is:
DateTime.ParseExact(rawDate.Substring(2), "ssmmHHddMMyyyy", CultureInfo.InvariantCulture).ToString("ddMMyyyy");
Otherwise use the following for the time being:
DateTime.ParseExact(rawDate.Substring(2), "ssmmHHddMMyy", CultureInfo.InvariantCulture).ToString("ddMMyyyy");
In any case you can choose whatever format you wish in the ToString() method.
A regular expression will give you terse code with validation as a bonus:
var match = Regex.Match(rawDate, #"PR\d{6}(?<d>\d\d)(?<m>\d\d)(?<y>\d\d)");
string date = match.Groups["d"].Value + "/" + match.Groups["m"].Value + "/20" + match.Groups["y"].Value;

Save two TextBox as DateTime asp.net C#

I have two textBox in first i have Date in this format : 2012.09.20 and in the second i have Time in this format: 15:30:00. In database i have Column name "Eventstart" type: DateTime. Now i like to take the value from two textbox and put them in something like this:
DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + Convert.ToDateTime(TextBoxTimeEnd.Text);
But give me this error : Error 2 Operator '+' cannot be applied to operands of type 'System.DateTime' and 'System.DateTime'
It sounds like you should be using:
DateTime date = Convert.ToDateTime(TextBoxEnd.Text);
DateTime time = Convert.ToDateTime(TextBoxTimeEnd.Text);
DateTime combined = date.Date + time.TimeOfDay;
Or you could combine the text and then parse that:
DateTime dateTime = Convert.ToDateTime(TextBoxEnd.Text + " " +
TextBoxTimeEnd.Text);
I'm not sure I'd use Convert.ToDateTime at all though - if you know the exact format that the textbox will be in, you should use DateTime.TryParseExact. You should work out which culture to use in that case though. If it's a genuinely fixed precise format, CultureInfo.InvariantCulture might be appropriate. If it's a culture-specific format, then use the user's culture.
You might also want to use an alternative UI representation which doesn't use textboxes at all, which would avoid potentially troubling string conversions.
Concatenate your TextBoxes text and use DateTime.ParseExact with format "yyyy.MM.dd HH:mm:ss"
After concatenating the text you should have: "2012.09.20 15:30:00"
DateTime dt = DateTime.ParseExact(TextBoxEnd.Text + " " + TextBoxTimeEnd.Text,
"yyyy.MM.dd HH:mm:ss",
CultureInfo.InvariantCulture);
Have you tried something like
DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + TimeSpan.Parse(TextBoxTimeEnd.Text);
First concatenate both the values and then add it to a DateTime variable
example:
string str = date.Text + time.Text; // assumed date and time are textboxes
DateTime dt=new DateTime();
DateTime.TryParse(str,dt); // returns datetime in dt if it is valid

exception thrown "String was not recognized as a valid DateTime" what to do?

This is my code.but value cannot inserted in database. it takes system datetime except selected value by drop down list.
string strDateOfBirth = ddlMonth.SelectedValue.ToString();
strDateOfBirth = strDateOfBirth + "/" + ddlBirthDate.SelectedValue.ToString();
strDateOfBirth = strDateOfBirth + "/" + ddlYear.SelectedValue.ToString();
//objVivah.BirthDate = DateTime.ParseExact(strDateOfBirth, "MM/dd/yyyy hh:mm", null);
objVivah.BirthDate = Convert.ToDateTime(strDateOfBirth);
// objVivah.BirthDate = Convert.ToString(strDateOfBirth);
To convert a String to a DateTime using the Convert.ToDateTime function, the String must be in a specific format. If your String has a different format you need to convert it using DateTime.ParseExact function:
DateTime.ParseExact(strDateOfBirth, "MM/d/yyyy", CultureInfo.InvariantCulture);
Try this:
objVivah.BirthDate = DateTime.ParseExact(strDateOfBirth, "MM/dd/yyyy", null);
You might want to have a look at TryParse as well.
Well, I wouldn't create the string to start with - if you already have each part, you can parse those as integers (using int.Parse) and then create a DateTime from that. Or for the drop-down lists, you may be able to avoid even having the string value to start with, which would be ideal. (Make the value associated with each item just an integer. This may not be feasible depending on what UI technology you're using - you haven't said whether it's WinForms, ASP.NET, WPF etc.)
Using DateTime.ParseExact with an appropriate format string is the second best way to go, but I don't see any point in creating a string only to then parse it.

Categories