I have a Datetime object which I take from an XML file (closingDate).
I want to dynamically display all closingDates to the user. However, not all objects in the XML file necessarily contain a dateobject.
How can I do this (pseudocode):
DateTime closingDate = DateTime.Parse(xmlFile.selectSingleNode("Closing_Date")).toString();
and then later, I am writing out an HTML file with:
String fileListHTML += "<li><a href='#'>The file name gets put here</a> (Closed:
"+closingDate+")</li>";
Now, as long as there is a datetime, there is no issue. However, if there is no datetime object (ie: null), I get an error.
Can I somehow do an if statement to say (again, pseudo):
if (closingDate =="")
{
closingDate = "To be determined";
}
I am, of course, getting an error about casting a datetime to string.
Is there a way to do this?
I'm not a fan of turning DateTimes to strings until it is necessary.
You could use a nullable DateTime. Use null to denote it's not set or parsable. Alternatively scratch the nullable approach and use a sentinel such as DateTime.MinValue instead.
This is untested but should get the point across:
DateTime? closingDate;
if (!string.IsNullOrEmpty(myClosingDateString))
{
closingDate = DateTime.Parse(myClosingDateString);
}
// do whatever else you need
// when it comes time to appending ...
if (!closingDate.HasValue) // or check if it's `DateTime.MinValue`
{
fileListHtml += "No closing date";
}
else
{
fileListHtml += closingDate.Value.ToString();
}
I'd caution you to be careful about converting DateTime to strings without considerations to time zones and internationalization (for example, DateTime.Parse() can interpret dates very differently depending on regional settings and/or the culture you pass in).
For simplicity, if you can control the format of the string, I'd suggest using UTC and the ISO 8601 format.
Use DateTime.TryParse instead, here's a sample code showing how it works:
DateTime res;
if ( DateTime.TryParse(str,out res))
{
// Res contain the parsed date and you can do whatever you want with
}
else
{
// str is not a valid date
}
http://msdn.microsoft.com/fr-fr/library/ch92fbc1.aspx
Related
I have two objects of type string, where I retrieve a date in dd/MM/yyyy format, I need to format this date I'm getting to show only month and year, in order to use this object in a groupby to group records by month. I'm doing it as follows, retrieving the date in another object to apply the formatting:
//Object where I retrieve the date with dd/MM/yyyy normally
public string DataCupom { get; set; }
//Object where I retrieve the value of DataCupom and I'm trying to apply the formatting
public string DataCupomAgrupadoMes { get { return String.Format("{MM:yyyy}", DataCupom); }
How can I apply String.Format correctly to retrieve only month and year?
A string is just a sequence of characters. It has no "date" or "time" semantics. Thus, attempting to format a sequence of characters (sucha as the DataCupom string) like it being some data type representing dates or time is not going to work.
In your case, one of the simplest approaches would probably be splitting the DataCupom string using '/' as separator, and then assemble the new required string from those parts of the split which represent month and year.
var parts = DataCupom.Split('/');
return $"{parts[1]}:{parts[2]}";
You can try parsing dateString to DateTime and then format.
DateTime dateTime = DateTime.Parse(dateString);
dateTime.ToString("MM/yyyy");
String.Format() uses numeric placeholders:
return String.Format("{0:MMyyyy}", DataCupom);
Where the 0 in the format string means to look at the first additional argument position for the value.
You can also use interpolation:
return $"{DataCupom:MMyyyy}";
or a simple ToString() call:
return DataCupom.ToString("MM:yyyy");
Please, how I can convert date string from my csv import to grid and mysql database?
I import date in dd.MM.yyyy format and I must format yyyy-MM-dd for mysql database.
my code for datagrid rows is
dataGridView1.Rows.Add(counter, "1", lineIn[0], ControlPrice, lineIn[3]);
lineIn[0] is date string...
Thank you
Its best to use DateTime.ParseExact
Based on your example, you need to cast to string before passing to the function.
You should also consider what happens if an invalid date is in the CSV, how do you want to handle that? Or do you always expect a date and want to halt processing?
Here's a LinqPad example I used to test:
object date = "12.2.2014";
var result = DateTime.ParseExact(date.ToString(), "d.M.yyyy", null).ToString("yyyy-MM-dd");
Console.WriteLine(result);
See this SO post for more info: DateTime Conversion and Parsing DateTime.Now.ToString(“MM/dd/yyyy hh:mm:ss.fff”)
Just in case your record might come as blank, it will give error while parsing to datetime, so I have added a condition to check for blank and then converted it to the required format.
If(lineIn[0].ToString() != "")
{
dataGridView1.Rows.Add(counter, "1", DateTime.ParseExact(lineIn[0].ToString(), "dd.MM.yyyy", null).ToString("yyyy-MM-dd"), ControlPrice, lineIn[3]);
}
else
{
dataGridView1.Rows.Add(counter, "1", "", ControlPrice, lineIn[3]);
}
This should work for you:
var parsedDate = DateTime.ParseExact(lineIn[0], "dd.MM.yyyy", null);
string dateStringInAnotherFormat = parsedDate.ToString("yyyy-MM-dd");
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
txtDatumDokum.Text is like "09.09.2011".
but i get FormatException error. Must i parse date?
Try DateTime.ParseExact with the dd.MM.yyyy format string
DateTime.ParseExact(txtDatumDokum.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
It's not good to see, anyway try this:
string s = "09.09.2011";
DateTime dt = Convert.ToDateTime(
s.Replace(".",
new System.Globalization.DateTimeFormatInfo().DateSeparator));
You need to tell us why the text input is using this format. If it is because the user enters it this way, then you need to make sure that the format matches that given by Thread.CurrentCulture.DateTimeFormat.ShortDatePattern. Changing the culture (by setting
Thread.CurrentCulture) to an appropriate value will then solve your problem.
If you are supposed to parse the input no matter what format it is in, then you will need to do some manual processing first (perhaps remove spaces and other delimiter characters from the input with string.Replace) and then try to parse the date using DateTime.ParseExact and a known format string.
But it all depends on why the input has that format, and why your application's current culture does not match it.
You could try this, TryParse avoids parsing exceptions.. Then you just need check result to be sure that it parsed.
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, out datuMDokumenta);
You will have to determine if this is a good solution for your application.
See this example:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
Judging by the date you gave you need to include a culture, de-DE accepts 01.01.11 type of dates but I'm not sure which one you actually want to use, you'll need to decide that.. the Code would look like this:
using System.Globalization;
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, CultureInfo.CreateSpecificCulture("de-DE"), DateTimeStyles.None, out datuMDokumenta);
A list of cultures can be found here, select the appropriate one for you:
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx
The plus here is that this code is a bit more work but it is very difficult to break. Assuming you are using a free text entry on a TextBox you don't want to be throwing exceptions.
Yes you have to parse input date in current culture.
string[] format = new string[] { "dd.MM.yyyy" };
string value = "09.09.2011";
DateTime datetime;
if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out datetime))
//Valid
else
//Invalid
DateTime dt = Convert.ToDateTime(txtDatumDokum.Text)
It is right...there is no isssue
During a Deserialization call under compact framework 3.5 i've had some unexpected behaviour before.
I've converted from using the OpenNETCF serialization classes to the framework XML serialization class. In doing so, the default time format has changed and the order of property/public members. So long story short, i've exposed a text property which converts my date-times back to the format my VB6 application is expecting.
Dim dumbDate As New Date
Dim formats() As String = {"yyyy-MM-ddTHH:mm:ss.fffzzz", _
"yyyy-MM-dd HH:mm:ss:fffffffzzz"}
_datetimeTaken = dumbDate.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
' There is something wrong with compact framework during the Serialization calls.
' calling the shared method Date.Parse or Date.ParseExact does not produce the same
' result as calling a share method on an instance of Date. WTF?!?!?!
' The below will cause a "Format" exception.
'_datetimeTaken = Date.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
Date.blah doesn't work. dumbDate.blah works. strange.
public static void Main(string[] args)
{
var dt = new DateTime(2018, 04, 1);
Console.WriteLine(dt);
string month = dt.ToString("MMMM");
Console.WriteLine(month); //April
month = dt.ToString("MMM");
Console.WriteLine(month); //Apr
month = dt.ToString("MM");
Console.WriteLine(month); //04
Console.ReadKey();
}
your code:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
try changing this to:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum);
and when u print the date/time
print datuMDokumenta.Text
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.
I am using LINQ and have a few properties thats DateTime? type.
If i now want to add the value from a textbox i cant seem to get this to work.
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ScoringLastUpgrade", DbType="Date")]
public System.Nullable<System.DateTime> ScoringLastUpgrade
The textbox i use i have made sure with javascript that the format will be '2011-06-17'
But now when i try to do this:
myObject.ScoringLastUpgrade = Convert.ToDateTime(txtScoringUpgradeDate.Text).ToShortDateString();
I get this error: "Cannot convert type string to DateTime?"
How to do this?
The .ToShortDateString() call is converting it into a string. You should remove that call.
Also, you say you've made sure of the format with javascript. What if the user doesn't have javascript, you should do server-side checks too. Also, since it's in a given format, you can use DateTime.ParseExact or DateTime.TryParseExact (so an invalid format doesn't throw an exception) since its more efficient. (The format string would be "yyyy-MM-dd") i believe.
Don't convert it to string using 'ToShortDateTimeString', just set the result of Convert.ToDateTime:
myObject.ScoringLastUpgrade = Convert.ToDateTime(txtScoringUpgradeDate.Text);
Assuming you've done sufficient validation on txtScoringUpgradeDate.Text?
My preference when dealing with these type conversions is to use the TryParse method, e.g.:
DateTime date;
if (DateTime.TryParse(txtScoringUpgradeDate.Text, out date))
myObject.ScoringLastUpgrade = date;
The Convert.ToDateTime, much like the explicit DateTime.Parse will throw an InvalidCastException when an excepional value occurs. It's better to make your code fault tollerant then needlesly catch an exception.
UPDATE: based on your last comment:
You shouldn't return DateTime.MinValue in this case, as MinValue is less than the supported min value of a datetime column. the CLR DateTime supports a date range down to 0000-01-01, whereas the SQL datetime (as well as the comparative CLR SqlDateTime type) supports a minimum value of 1753-01-01. As it as a nullable DateTime, you should set it to null:
public static DateTime? ToNullableDateTime(this string date)
{
DateTime dateTime;
return (DateTime.TryParse(date, out dateTime))
? (DateTime?)dateTime
: null;
}
The problem is that you have put ToShortDateString() at the end there, effectively converting the DateTime back to a string again. Try removing that part of the line.
In my case (.cshtml):
<td>#item.InvoiceDate.Value.ToShortDateString().ToString()</td>
Where InvoiceDtae is Nullable Date in DB