I am getting this: 9/13/2011 12:00:00 AM
from my DB and I want to show like this:
9/13/2011
This is my code for this:
litDate.Text = Obj1.DueDate.ToString();
My DueDate is of this property:
public DateTime? DueDate { get; set; }
Try this:
litDate.Text = Obj1.Date.ToString("MM/dd/yyyy");
Use the formatter "d", only if Obj1.Date is of type DateTime.
if(Obj1.DueDate.HasValue)
{
litDate.Text = Obj1.DueDate.Value.ToString("d");
}
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
This gives all the standard date format strings with examples.
Here is the example you want:
// Display using current (en-us) culture's short date format
DateTime thisDate = new DateTime(2008, 3, 15);
Console.WriteLine(thisDate.ToString("d"));
// Displays 3/15/2008
The answers that explicitly format the string should not be used in any case where you might have to internationalize the date. This answer uses the culture context of the user's computer.
litDate.Text = Obj1.Date.ToShortDateString();
Along with insta's answer, you can also use
litDate.Text = Obj1.Date.ToString("MM/dd/yyyy");
http://www.csharp-examples.net/string-format-datetime/
EDIT: Now that you revised your question to a COMPLETELY DIFFERENT datatype, you need to learn how Nullables work. Check .HasValue, and if so, then .Value will be a DateTime, making all the rest of these answers relevant again.
Related
I have to parse a string, which always look like 03/2020 (so the format is MM/yyyy), to a DateTime variable.
How do I achieve it the most proper way? (Without splitting the string into substrings)
I already found the DateTime.ParseExact function, but I'm confused by the third parameter (culture-specific format information).
Is the DateTime.ParseExact the way to go or is there a better function/way to achieve the goal?
var inputString = "03/2020";
var inputStringFormat = #"MM/yyyy";
// var inputStringAsDateTime = ???
Edit 1
As additional info I have to say, that the string (inputString) is read from a barcode. So the separator in it is always the /.
Tim Schmelter explained in his answer, how to mask such separators.
It looks like I have to change my inputStringFormat variable to:
var inputStringFormat = #"MM'/'yyyy";
If the first day of the month is good for you, you can use DateTime.ParseExact:
var d = DateTime.ParseExact(inputString, inputStringFormat, CultureInfo.InvariantCulture);
Usually, i use ToDateTime method of Convert class. I have tested it, it's working.
string inputString = "03/2020";
DateTime datetime = Convert.ToDateTime(inputString));
It will give output like 3/1/2020 12:00:00 AM means it will gives you output according to your system's date format.
With such simple date format you can use
var inputArr = inputString.split(#"/");
var inputStringAsDateTime = new DateTime(inputArr[0], inputArr[1], 1);
however for culture you can use constant
CultureInfo.InvariantCulture
I try to display a DateTime with the "general date short time" format.
When I use the g specifier, it gives me something like 01-08-13 10:12:00 10:12 instead of 01-05-13 10:12.
It seems to duplicate the time and I don't know why.
Anyone?
Edit 1
Here is the code I use:
var startDate = DateTime.MinValue.ToString("g");
if (Airspace.StartDate != null)
startDate = ((DateTime)Airspace.StartDate).ToString("g"); //01-08-13 00:00:00 00:00
Edit 2
The same issue occurs when I use "short date pattern":
var startDate = DateTime.MinValue.ToString("d");
if (Airspace.StartDate != null)
startDate = ((DateTime)Airspace.StartDate).ToString("d"); //01-08-13 00:00:00
It doesn't make sense!
The "d" format specifier applies the short date pattern and "g" is a concatenation of the short date and short time patterns. So based on your results, you somehow have a short date pattern with time components in it. I can reproduce your results by setting such a short date pattern explicitly, like so:
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine(DateTime.Today.ToString("g")); // 2008-05-11 00:00:00 00:00
Console.WriteLine(DateTime.Today.ToString("d")); // 2008-05-11 00:00:00
I think the real question is how you ended up with what looks like some very strange culture settings! I tried enumerating the set of supported cultures and looking for one whose short date format included time specifiers, like so:
foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures)
.OrderByDescending(c => c.DateTimeFormat.ShortDatePattern.Length))
{
Console.WriteLine($"{culture.Name} {culture.DateTimeFormat.ShortDatePattern}");
}
But in several hundred cultures I came up with nothing. So, can you find anything anywhere in your code that's building up a CultureInfo object and assigning it as the current culture? If yes, maybe there's a mistake in that code somewhere.
Hope this can help you:
DateTime today = DateTime.Now;
Console.WriteLine(today.ToString("dd-MM-yy H:mm"));
//Result: 01-08-13 04:33
Console.ReadLine();
Other format: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
Try this
startDate = DateTime.Now.ToString(System.Globalization.CultureInfo.
CurrentCulture.DateTimeFormat);
I have to retrieve a date from the database in format YYYY-MM-DD and display it as the format:
Mon 25th
Currently my code looks like:
Label fixtureDateLabel = new Label();
fixtureDateLabel.Text = dReaderGameweekFixtures["fixtureDate"].ToString();
How do I adapt this to display in the format I want?
You can do this using the ToString method:
var result = DateTime.Parse(
dReaderGameweekFixtures["fixtureDate"].ToString()
).ToString("ddd dd");
To my knowledge you'll need a little something extra to formulate the suffix to the day number, which is already conveniently provided here.
You need to format the string according to one of the available formats:
http://msdn.microsoft.com/en-gb/library/az4se3k1.aspx
Pass it to ToString method.
Have go on the link below, would suffice your need and increase your knowledge...
http://www.dotnetperls.com/datetime-format
You should use ToString method of DateTime with format parameter
Check some info here - http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Label fixtureDateLabel = new Label();
DateTime d = dReaderGameweekFixtures["fixtureDate"];
fixtureDateLabel.Text = d.ToString("yyyy-MM-dd");
I have date in this format "1999-05-31T13:20:00.000-05:00" I want to add some hours or days to it . Can some one suggest how to do that with this format and AddDays or AddHours ? Result need to return same format.
Try using DateTimeOffset.Parse. Then use AddDays or AddHours.
It is important to use DateTimeOffset instead of DateTime if you want to preserve the same timezone offset that you parsed.
var dateTimeOffset = DateTimeOffset.Parse("1999-05-31T13:20:00.000-05:00");
var newDateTimeOffset = dateTimeOffset.AddHours(1);
var newDateTimeString = newDateTimeOffset.ToString("O");
if you don't like the way "O" formats, you can use this:
var newDateTimeString = newDateTimeOffset.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK")
This will 100% match to your format.
Example:
txt_del.Text = Calendar1.SelectedDate.ToString("MM/dd/yyyy");
/* for date picking textbox*/
double d2 = double.Parse(txt_till.Text);
/*second textbox for number of days to add*/
DateTime tom = Calendar1.SelectedDate.AddDays(d2);
/*for adding number of days to selected date*/
txt_total.Text = tom.ToString("MM/dd/yy")
Use DateTime.Parse(...) to create a DateTime object. Then you can add days and/or hours, and then ToString() to get the new string.
That looks like datetimeoffset. Perhaps from sql server? You should be able to use the datetimeoffset structure and the parse method. Once you have a datetimeoffset type you can use addhours or related methods.
I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
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;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message