Custom DateTime formatting in c# - c#

I have a variable which is printed out using the following string format:
var printThis = String.Format("{0:d}, {0:T}", dateAndTimeVar);
Now I have a problem; I need '{0:T}' to display something like '--.--.--' when I have not set any time to the 'dateAndTimeVar'. This seems not supported using the regular DateTime type (showing '00.00.00' by default if there is no time set).
I can change the 'dateAndTimeVar' variable to anything (including other types), but the string formatting must remain the same.
Is there any solution to this?

You would need to create your own IFormatProvider and pass it into the String.Format method like this
String.Format(new MyFormatProvider(), "{0:d}, {0:T}", dateAndTimeVar);
The FormatProvider would then do a pass-through on all formats except T, where you would have your logic for outputting either the native T format for DateTime or --.--.-- if the Time-part of DateTime is 00:00:00.
Read about IFormatProvider on MSDN here

This a list of date time patterns you can use
DateTime.ToString() Patterns | GeekZilla
Cheers

You could simply check if the DateTime contains a time:
String printThis = dateAndTimeVar.Date == dateAndTimeVar ?
String.Format("{0:d}, --.--.--", dateAndTimeVar) :
String.Format("{0:d}, {0:T}", dateAndTimeVar);

You could simply do this:
var printThis = String.Format("{0:d}, {0:T}", dateAndTimeVar)
.Replace("00:00:00", "--.--.--");

Related

Datetime parse not working for specific format

Hello experts i am not able to parse the datetime object from following format
2019-12-04T04:26:29:00
in c#. When I trying to parse this format I'll get
04-12-2019 04:26:29
Without T as DateTime object
You can use the ToString() function in the following way to format your DateTime:
DateTime yourDateTime = ...//your DateTime value
yourDateTime.ToString("dd/MM/yyyy HH:mm:ss")//or any other format
You can parse user input like this:
DateTime enteredDate = DateTime.Parse(enteredString);
If you have a specific format for the string, you should use the other method:
DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);
"d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.
Remove the last 2 zeros and try.
Your code is
2019-12-04T04:26:29:00
The suggested code change is
2019-12-04T04:26:29

What is a less Kludgy way to Conditionally Prepend a "0" to dateTime Elements?

I want my string YearMonthDayHourMinuteSecondMillisecond to be of this format ("0" prepended where necessary):
20140227142807
...but this:
string YearMonthDayHourMinuteSecond = string.Format("{0}{1}{2}_{3}{4}{5}", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
...gives me "2" (instead of "02") for February, etc. such as:
2014227142807
I can solve it this way:
string YearMonthDayHourMinuteSecondMillisecond = string.Format("{0}{1}{2}_{3}{4}{5}{6}", dt.Year, ConditionalZeroForepad(dt.Month), ConditionalZeroForepad(dt.Day), ConditionalZeroForepad(dt.Hour), ConditionalZeroForepad(dt.Minute), ConditionalZeroForepad(dt.Second);
private string ConditionalZeroForepad(string s)
{
if (s.Length < 2)
{
return string.Format("0{1}", s);
}
}
...but that's 9X Uglier than a Bag of Butts.
What is a more genteel way to accomplish this?
Don't use string.Format at all - use DateTime.ToString():
string text = dt.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);
Or to just go down to seconds:
string text = dt.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
(Your variable name suggests you want milliseconds, but your sample suggests you don't.)
Note the use of CultureInfo.InvariantCulture to ensure you always use the Gregorian calendar, even if the current culture of the thread is one which has a different default calendar. (Obviously if you want a different calendar, that's a different matter.)
See custom date and time format strings for more information.
You need to use a string format like:
var str = string.Format("{0:D2}", 2);
Value of str: 02
The D2 portion tells the formatter to make sure there is at least two digits in the formatted number. See this MSDN page for more on Custom Numeric Format Strings
But providing a date time format to DateTime.ToString is a better solution then trying to compose the format you want from the individual parts.
string YearMonthDayHourMinuteSecondMillisecond = dt.ToString("yyyyMMddHHmmss")
You could use ToString() with a format parameter such as dt.Month.ToString("D2")

DateTime FormatException error

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

How to create a readable date and time from a string?

I'm using an api that returns the date as a string, like so:
2011-06-13T21:15:19Z
As you can imagine this is not the easiest format to understand. My goal is to get it to format like this:
9:15pm - 6/13/2011
Anyone know how to accomplish this? Do I need to use a regular expression or is there a way to convert this to a DateTime?
NOTE: I have tried to use the DateTime.ParseExact method but it didn't work. If this is the solution could you please show me how to convert the example above. Thanks.
string date = "2011-06-13T21:15:19Z";
DateTime dt = DateTime.Parse(date);
I just tried it with TryParse and it worked. Using a try parse is better than parse because you can then handle for the cases the string didn't parse. If your certain the string being passed is static, then I guess it isn't necessary.
string Time = "2011-06-13T21:15:19Z";
DateTime t;
if (DateTime.TryParse(Time, out t))
{
//Works
}
DateTime.Parse seems to work fine for that string:
var dt = DateTime.Parse("2011-06-13T21:15:19Z");
Console.WriteLine(dt.ToString("h:mmtt - M/d/yyyy"));
EDIT
If you want to get it the formatted string to look exactly how it is in your question, just throw a ToLower() on it:
Console.WriteLine(dt.ToString("h:mmtt - M/d/yyyy").ToLower());
Also, all of the date and time string formatting options can be found here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
DateTime.Parse is supposed to work with those ISO 8601 date strings.
Use DateTime.Parse.
void Main()
{
var date = DateTime.Parse("2011-06-13T21:15:19Z");
Console.WriteLine(date);
}
The format string you are looking for is "hh:mmtt \- M/d/yyyy".

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