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);
Related
I keep getting the error of "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0." but I am unsure as the reason why.
//Date and Age
String months = Convert.ToString(txtMonth);
String days = Convert.ToString(txtDay);
String year = Convert.ToString(txtYear);
String DOB = days + " " + months + " " + year;
int age = AgeCalc(DOB);
//Age Function
private int AgeCalc(string date)
{
DateTime DOB = Convert.ToDateTime(date);
DateTime Year = DateTime.Now;
TimeSpan span = Year - DOB;
DateTime Age = DateTime.MinValue.AddDays(span.Days);
return Age.Year - 1;
}
//Separate Box
MessageBox.Show("First Name:" + fName + "\nLast Name:" + lName + "\nGender:" + gender + "\nAge:" +
age + "\nHeight (in inches):" + height + "\nWeight (lbs):" + weight + "\nMax Heart Rate:" + heartRate +
"\nTarget Heart Rate:" + targetRate + "\nBMI:" + BMI, "Result");
More code provided on request.
If you want to detect if the user entered the wrong value try this
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"};
if (DateTime.TryParseExact(date, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime DOB))
{
// DOB variable is ready to use
Label1.Text = DOB.ToShortDateString();
} else {
//error handling goes here
Label1.Text = "ERROR: Invalid value";
}
DOB.ToShortDateString() will convert back into a string.
Assume that you only allow users to input correct value (valid integer). You can use this
new DateTime(Convert.ToInt32(txtYear), Convert.ToInt32(txtMonth), Convert.ToInt32(txtDay));
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));
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;
}
I've got a custom control on my page that has a field for Hours, Minutes, and AM/PM. I need to be able to take each string Hour + Minutes + AM/PM and get a valid TimeSpan so I can combine with a Date.
I've tried a couple different ways but get Invalid TimeSpan errors. Here is my code
string date = DateDropDown.SelectedValue;
string hour = HourDropDown.SelectedValue;
string minute = MinuteDropDown.SelectedValue;
string timeofDay = AMPMDropDown.SelectedValue;
string timeStr = hour.PadLeft(2, '0') + ":" + minute + timeofDay;
TimeSpan custTime = TimeSpan.Parse(timeStr);
DateTime custDate = DateTime.Parse(date);
DateTime callBackDT = custDate.Add(custTime);
Aside from considering errors with the Parse. How can I get a valid timespan from with the time strings and am/pm?
Thanks
Just parse the DateTime once, at the end:
string date = DateDropDown.SelectedValue;
string hour = HourDropDown.SelectedValue;
string minute = MinuteDropDown.SelectedValue;
string timeofDay = AMPMDropDown.SelectedValue;
string dateStr = date + " " + hour.PadLeft(2, '0') + ":" + minute + " " + timeofDay;
DateTime callBackDT = DateTime.Parse(dateStr);
There is no reason to build a TimeSpan in this case, as DateTime.Parse can handle dates with times as a single DateTime.
If you don't have to use TimeSpan, just parse the entire string with DateTime.Parse:
var timeStr = string.Format("{0} {1}:{2} {3}", date, hour.PadLeft(2, '0'), minute, timeofDay);
var callBackDT = DateTime.Parse(timeStr, CultureInfo.CreateSpecificCulture("en-US"));
// Or whatever culture your string will be formatted with
TimeSpan objects don't have a concept of am / pm. You'd have to use a DateTime instead:
string timeStr = hour.PadLeft(2, '0') + ":" + minute.PadLeft(2, '0') + " " + timeofDay;
DateTime custDate = DateTime.ParseExact("HH:mm t", timeStr, null);
TimeSpan custTime = custDate.TimeOfDay;
Further Reading
Custom Date and Time Format Strings
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.