C# String to date with CultureInfo - c#

I have a date in the following format. It is always in this format.
yyyyMMdd -> 20130912
I need to convert it to a date. But I need to be sure that the date is converted to the correct date format of the PC. Cultureinfo.InvariantCulture. Here is what my code looks like now.
DateTime parsedDateTime;
int year = Int32.Parse(rows[row][4].ToString().Substring(0, 4));
int month = Int32.Parse(rows[row][4].ToString().Substring(4, 2));
int day = Int32.Parse(rows[row][4].ToString().Substring(6, 2));
DateTime value = new System.DateTime(year, month, day);
bool DateTimeParseFail = DateTime.TryParse(value.ToString("yyyy-MM-dd"), CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime);
if (!DateTimeParseFail) {
msg = "Data Feed Convert string to DateTime: Date " + rows[row][4].ToString() + " - " + value.ToString();
ComponentMetaData.FireError(0, ComponentMetaData.Name, msg, string.Empty, 0, out pbCancel);
throw new Exception(msg);
} else {
buffer[colIndex] = parsedDateTime;
}
This just looks like overkill to me and I suspect that I'm over-thinking it. There has to be an easier way of doing this. But everything I have tried hasn't worked like I expected it.

Try this:
string dateText = rows[row][4].ToString();
DateTime date = DateTime.ParseExact(dateText, "yyyyMMdd", CultureInfo.InvariantCulture);
string result = date.ToShortDateString(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern);
Note that I'm assuming your assertion that the date is always in this format is correct. If it's not, you'll find that the code throws an exception.
(The code you've posted suggests that your assertion is not true, because you've got a fallback format and some failure handling there...)

Use the TryParseExact of DateTime....
var dateString = "20130912"; //rows[row][4].ToString()
DateTime parsedDateTime;
var DateTimeParseFail= DateTime.TryParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime);
if (!DateTimeParseFail) {
msg = "Data Feed Convert string to DateTime: Date " + rows[row][4].ToString() + " - " + value.ToString();
ComponentMetaData.FireError(0, ComponentMetaData.Name, msg, string.Empty, 0, out pbCancel);
throw new Exception(msg);
} else {
buffer[colIndex] = parsedDateTime;
}

Related

Changing Language of DateTime Error

So I am trying to change the language of a DateTime in C# from English to French. It was working perfectly yesterday, made a few changes (that had nothing to do with the date at all) come back today and am running into this error:
An exception o type System.FormatException occured in msorlib.dll but was not handled in user code. Additional Information: String was not recognized as a valid DateTime.
Here is my code:
string period;
period = Convert.ToString(Request.QueryString["Period"]);
string format = "dddd, MMMM dd, yyyy";
string fDate = from.ToLongDateString();
var fr = DateTime.ParseExact(fDate, format, new CultureInfo("en-US"));
var fromDate = fr.ToString("D", new CultureInfo(this.BGUser.UICultureInfoString));
string tDate = to.ToLongDateString();
var td = DateTime.ParseExact(tDate, format, new CultureInfo("en-US"));
var toDate = td.ToString("D", new CultureInfo(this.BGUser.UICultureInfoString));
if (period == null)
return "<b>" + this.Translate("Orders due ", 4386) + fromDate + " - " + toDate + "</b>";
else if (period.Equals("archive"))
return "<b>" + this.Translate("Orders due before ", 4387) + toDate + "</b>";
else if (period.Equals("future"))
return "<b>" + this.Translate("Orders due after ", 4388) + fromDate + "</b>";
It is specifically getting the error on the line
var fr = DateTime.ParseExact(fDate, format, new CultureInfo("en-US"));
The from and to are DateTime variables that are passed into the function and are correct. Any help is much appreciated!
Thanks for the comments. I took your comments into account and did this which seems to work
var fromDate = from.ToString("D", new CultureInfo(this.BGUser.UICultureInfoString));
var toDate = to.ToString("D", new CultureInfo(this.BGUser.UICultureInfoString));

DateTime to String

I want to have the datetime in my file, like this:
Date 2014.03.20 11.41.06
or german 20.03.2014 11.41.06
but it does not work. If i try to convert the DateTime to string i get:
1.1.1 0.0.0
What's wrong with this?
DateTime DateAndTime = new DateTime();
int day = DateAndTime.Date.Day;
int month = DateAndTime.Date.Month;
int year = DateAndTime.Date.Year;
int second = DateAndTime.Date.Second;
int minute = DateAndTime.Date.Minute;
int hour = DateAndTime.Date.Hour;
string sday = day.ToString();
string path = day + "." + month + "." + year + hour +
"." + minute + "." + second + " test.txt";
FileStream fileStream = new FileStream(expath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
You never set a DateTime value, so it defaulted to midnight on January 1st. If you want to use the current date then use DateTime.Now:
DateTime DateAndTime = DateTime.Now;
The DateTime value will be 0001.01.01 00.00.00 when using new DateTime(), it's better to use DateTime.Now if you want the current date and time:
var path = DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss") + " test.txt";
You can use CultureInfo to get the correct formatting for various regions. Since you mentioned German:
using System.Globalization;
CultureInfo deDE = new CultureInfo("de-DE");
string DateAndTime = DateTime.Now.ToString(deDE);
It will give you the following output, though:
20.03.2014 14:39:12
Example from http://www.dotnetperls.com/filename-datetime
Just do
string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin", DateTime.Now);

Creating DateTime object from string

I currently am reading from a text file an assortment of data, and parsing out everything. One of the items being parsed out is a start time for an event in the format of:
yyMMddHHmm
1306050232
I then parse out to the following:
string year = "20" + time[0].ToString() + time[1].ToString();
string month = time[2].ToString() + time[3].ToString();
string day = time[4].ToString() + time[5].ToString();
string hour = time[6].ToString() + time[7].ToString();
string minute = time[8].ToString() + time[9].ToString();
string ampm ="";
int hourInt = Convert.ToInt32(hour);
if (hourInt <= 12)
{
time = month + "." + day + "." + year + "#" + hour + ":" + minute + " " + "AM";
ampm= "AM";
}
else
{
hourInt = hourInt - 12;
time = month + "." + day + "." + year + "#" + hourInt.ToString() + ":" + minute + " " + "PM";
ampm= "PM";
}
once these are parsed out, i combined the variables, and try to put it into a DateTime.
string tempStartTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + " " + ampm;
string starttime = DateTime.ParseExact(tempStartTime, "yyyy-MM-dd HH:mm tt",null);
my issue is, I get a warning like this from the try catch:
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
at Project.GUI.parseSchedule(Int32 count)
I don't understand why, or how to correctly do this.
All I want is to take the start time from the file, convert it to a datetime object, and operate on it afterwards.
Why not simply parse with the format you are starting with?
var dt = DateTime.ParseExact(time, "yyMMddHHmm", CultureInfo.InvariantCulture);
There's no need for all of the pre-processing you're doing.
Parsing before parsing is generally quite unnecessary. If you have the input string
// yyMMddHHmm
string timestampString = "1306050232";
Then you should be able to do:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime timestamp = DateTime.ParseExact(timeStampString, "yyMMddHHmm", provider);
If not, I would like to have more information about the exact error you are getting.
Have a look at DateTime.ParseExact()
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
DateTime result=null;
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date and time with custom specifier.
string dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
string format = "ddd dd MMM yyyy h:mm tt zzz";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
You might want to look into custom formatters rather than trying to parse everything. I think that would make your code more maintainable, and probably somewhat easier to decode. There's a tool linked on that page that would let you test your format string before putting it into code, as well.

date validation hotel reservation

hi iam creating a hotel reservation form and wanted to calculate total cost of stay by the nights stayed. it requires an arrival date and departure date but i want to add a validation so if the user inputs an incorrect format a message box displays asking them to try again. here is my code already had a bit of help with converting the timespan so once again any help would be amazing. the error is on the line that begins "dateDiff = aDate" and it says the variables aDate and dDate are unassigned thanks in advance:
String arrival, departure;
arrival = textBox1.Text;
departure = textBox2.Text;
DateTime aDate, dDate;
try
{
aDate = DateTime.ParseExact(arrival, "dd/mm/yyyy", null);
dDate = DateTime.ParseExact(departure, "dd/mm/yyyy", null);
return;
}
catch
{
MessageBox.Show("Invalid input format please enter in format DD/MM/YYYY");
}
TimeSpan dateDiff;
dateDiff = dDate.Subtract(aDate);
int nights = (int)dateDiff.TotalDays;
textBox3.Text = ("" + nights);
textBox5.Text = ("£" + (nights * 115));
The reason for the compiler warning is that you haven't assigned a value to your local DateTime fields. Local variables are not initialized with a default value, hence you must do it manually before you can use them. Since you assign the value in a Try/Catch it's not ensured that they will ever get one.
Instead you could use DateTime.TryParseExact:
DateTime aDate, dDate;
if( DateTime.TryParseExact(arrival, "dd/mm/yyyy", null, DateTimeStyles.None, out aDate)
&& DateTime.TryParseExact(departure, "dd/mm/yyyy", null, DateTimeStyles.None, out dDate))
{
// ...
}
else{
MessageBox.Show("Invalid input format please enter in format DD/MM/YYYY");
}
Your code it continuing after your catch. Place the code using the dates within your try-block.
String arrival, departure;
arrival = textBox1.Text;
departure = textBox2.Text;
DateTime aDate, dDate;
try
{
aDate = DateTime.ParseExact(arrival, "dd/mm/yyyy", null);
dDate = DateTime.ParseExact(departure, "dd/mm/yyyy", null);
TimeSpan dateDiff;
dateDiff = dDate.Subtract(aDate);
int nights = (int)dateDiff.TotalDays;
textBox3.Text = ("" + nights);
textBox5.Text = ("£" + (nights * 115));
}
catch
{
MessageBox.Show("Invalid input format please enter in format DD/MM/YYYY");
}
And don't return if they parse successfully, or you'll have no result when your input does validate.
Alternatively, place the return in your catch-block, so that execution is stopped on failure.
Your code should be
String arrival, departure;
arrival = textBox1.Text;
departure = textBox2.Text;
DateTime aDate, dDate;
try
{
aDate = DateTime.ParseExact(arrival, "dd/mm/yyyy", null);
dDate = DateTime.ParseExact(departure, "dd/mm/yyyy", null);
TimeSpan dateDiff;
dateDiff = dDate.Subtract(aDate);
int nights = (int)dateDiff.TotalDays;
textBox3.Text = ("" + nights);
textBox5.Text = ("£" + (nights * 115));
}
catch
{
MessageBox.Show("Invalid input format please enter in format DD/MM/YYYY");
return;
}
Use dateTimePicker control you don't need to Parse
Assign some default values to your aDate, dDate, and the error will go away. The reason is that compiler can't determine if they will be assigned values for sure in the try block. You can do
DateTime aDate = default(DateTime);
DateTime dDate = default(DateTime);
BUT
instead of using try-catch to validate date, its better if you use DateTime.TryParseExact
DateTime aDate, dDate;
if (DateTime.TryParseExact(arrival,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.NoCurrentDateDefault,
out aDate))
{
MessageBox.Show("Invalid input format please enter in format DD/MM/YYYY");
}
So your complete code should be:
String arrival, departure;
arrival = textBox1.Text;
departure = textBox2.Text;
DateTime aDate, dDate;
if (DateTime.TryParseExact(arrival,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.NoCurrentDateDefault,
out aDate))
{
MessageBox.Show("Invalid input format for Arrival Date - please enter in format DD/MM/YYYY");
}
if (DateTime.TryParseExact(departure,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.NoCurrentDateDefault,
out dDate))
{
MessageBox.Show("Invalid input format for Departure Date - please enter in format DD/MM/YYYY");
}
TimeSpan dateDiff;
dateDiff = dDate.Subtract(aDate);
int nights = (int)dateDiff.TotalDays;
textBox3.Text = ("" + nights);
textBox5.Text = ("£" + (nights * 115));

convert datetime to date format dd/mm/yyyy

I have a DateTime object 2/19/2011 12:00:00 AM. I want to convert this object to a string 19/2/2011.
Please help me to convert DateTime to string format.
DateTime dt = DateTime.ParseExact(yourObject.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
First of all, you don't convert a DateTime object to some format, you display it in some format.
Given an instance of a DateTime object, you can get a formatted string in that way like this:
DateTime date = new DateTime(2011, 2, 19);
string formatted = date.ToString("dd/M/yyyy");
As everyone else said, but remember CultureInfo.InvariantCulture!
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)
OR escape the '/'.
You have to pass the CultureInfo to get the result with slash(/)
DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
DateTime.ToString("dd/MM/yyyy") may give the date in dd-MM-yyyy format. This depends on your short date format. If short date format is not as per format, we have to replace character '-' with '/' as below:
date = DateTime.Now.ToString("dd/MM/yyyy").Replace('-','/');
It's simple--tostring() accepts a parameter with this format...
DateTime.ToString("dd/MM/yyyy");
Here is a method, that takes datetime(format:01-01-2012 12:00:00) and returns string(format: 01-01-2012)
public static string GetDateFromDateTime(DateTime datevalue){
return datevalue.ToShortDateString();
}
You can use the ToString() method, if you want a string representation of your date, with the correct formatting.
Like:
DateTime date = new DateTime(2011, 02, 19);
string strDate = date.ToString("dd/MM/yyyy");
In C# 10 you can use DateOnly.
DateOnly date = new(2011, 02, 19);
string output = date.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
If you want the string use -
DateTime.ToString("dd/MM/yyyy")
On my login form I am showing the current time on a label.
public FrmLogin()
{
InitializeComponent();
lblTime.Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");
}
private void tmrTime_Tick(object sender, EventArgs e)
{
lblHora.Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");
}
string currentdatetime = DateTime.Now.ToString("dd'/'MM'/'yyyy");
DateTime.Parse(YOUR_DATE_OBJECT).ToShortDateString();
ToShortDateString() method will help you convert DateTime To Just Date String,format dd/mm/yyyy.
This works for me:
string dateTimeString = "21‎-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30";
dateTimeString = Regex.Replace(dateTimeString, #"[^\u0000-\u007F]", string.Empty);
string inputFormat = "dd-MM-yyyy HH:mm:ss";
string outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
string output = dateTime.ToString(outputFormat);
Console.WriteLine(output);
this is you need and all people
string date = textBox1.Text;
DateTime date2 = Convert.ToDateTime(date);
var date3 = date2.Date;
var D = date3.Day;
var M = date3.Month;
var y = date3.Year;
string monthStr = M.ToString("00");
string date4 = D.ToString() + "/" + monthStr.ToString() + "/" + y.ToString();
textBox1.Text = date4;

Categories