date month not displaying correctly - c#

why is
string date = string.Format("{0:mmddyyHHmmss}",
DateTime.Now);
giving me 420813104204
shouldn't it be 040813... ?
I am trying to match
mmddyyHHmmSS

You need to use MM for month not mm, mm is for minutes not months.
string date = string.Format("{0:MMddyyHHmmss}",
You can find more about formats here.

try this instead
string date = string.Format("{0:MMddyyHHmmss}", DateTime.Now);

string date = string.Format("{0:MMddyyHHmmss}", DateTime.Now);
would give you the required format.
Check out this link for reference

That's because mm is for the minute not months, you need to use MM. You can see the definition for custom date time strings here.
string date = string.Format("{0:MMddyyHHmmss}",
Further, I generally don't use string.Format with DateTime objects because I've seen some anomalies when it comes to parsing them across different cultures. Leveraging the ToString method on the DateTime object for me has always been more reliable. That's just something I've seen - it also could be that I was doing something wrong with the string.Format. I wish I could build an example of that right now but I don't even remember what those anomalies are now - I just remember having problems so I switched.

Related

DateTime.Now Returning Different Months on Different runs

I need to get the current date so that i can write a log file.
I use
DateTime.Now.ToString("yyyy-mm-dd")
But the month value-mm always keep changing.What im i doing wrong?
It should be
DateTime.Now.ToString("yyyy-MM-dd")
because mm stands for minutes, not months.
"mm" is the format string for minutes, not months. You want to use uppercase M instead, so use the format yyyy-MM-dd. For a list of all date and time related format strings have a look at the MSDN documentation for custom format strings.

How to remove hour, minutes and seconds from a date

I've two types of dates, one in DateTime format and another in string format, both dates having the following format:
yyyy-MM-dd HH: mm: ss
I want to delete HH: mm: ss because I need to compare these dates in a loop to iterate through a database. The problem's that one of these dates is returned by a CalendarSelectionDate event, and the hour, minutes and seconds are even set to 0. Anyone have the best way to do this?
UPDATE:
if (DateTime.TryParseExact(reader["data"].ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt)){...}
The code behavior return an invalid date, in particular if I've 12/05/15 ... the code will return 1/01/0001
If you want to compare DateTime objects without the hour, you can use the Date property:
if (myDbDate.Date != myUserDate.Date) { }
You can also cast the date to a string using ToString(), but be aware that dates are a notoriously very hard thing to deal with when they are strings:
if (myDbDate.ToShortDateString() != myUserDate) { }
or if you are very sure of your format, you can use a custom date format:
if (myDbDate.ToString("yyyy-MM-dd") != myUserDate) { }
Update
Automatically parsing the string to a date (with DateTime.Parse or TryParse) has often resulted, in my own and personal experience, in very random results. You never seem to know which format .Net will decide on using (dd/MM or MM/dd ?).
Using ParseExact or TryParseExact solves this problem, and allows to work on the date further (add days, for instance). But for a simple comparison as in the initial question, since you're "locking" the date format in the code, it doesn't change much (maybe performance-wise, I don't know), and it's much more simple to cast the date to a string than the other way.
That being said, I went on the assumption that the comparison was "is different". If the comparison is "is later/earlier than", casting to a date would indeed be the right solution.
First you have to understand that DateTime does not have a format. It only contains information that describes a specific point in time. Formats apply to the string representations of a DateTime. For what you want you can use DateTime.Date which will return a new DateTime with the same year, month, and day values, but with the time set to 12 AM. That along with DateTime.ParseExact will allow you to parse the string to a DateTime then compare just the Date part.
var someDate = DateTime.ParseExact(stringValue, "yyyy-MM-dd HH: mm: ss");
if(someDate.Date != otherDate.Date)
{
}
To get the base date of any DateTime, simply use the Date property.
DateTime.Now.Date

C# - Date/Time Formatting

Using C#, I am trying to format a date in to the following string format:
YYYYMMDD_HHMM.xlsx
Here is my code:
DateTime.Today.AddDays(0).ToString("yyyymmdd") + "_" + DateTime.Today.AddDays(0).ToString("hhmm")
Here is my output:
20130027_1200.xlsx
Month is not correct, nor is the time.
You're using mm, which is minutes, not months - and you're trying to print the time using DateTime.Today, which always returns midnight at the start of the day.
It's not clear why you're adding 0 days, either. I'd use:
DateTime now = DateTime.Now;
string name = now.ToString("yyyyMMdd'_'HHmm'.xlsx'");
(The ' quoting for the _ isn't strictly necessary, but personally I find it simplest to take the approach of quoting everything that isn't a format specifier.)
Or:
DateTime now = DateTime.Now;
string name = string.Format("{0:yyyyMMdd}_{0:HHmm}.xlsx", now);
Note the use of HH instead of hh to get a 24-hour clock rather than 12-hour, too.
Additionally, consider using UtcNow instead of Now, depending on your requirements. Note that around daylight saving transitions, the clock will go back or forward, so you could end up with duplicate file names.
Also note how in my code I've used DateTime.Now once - with your original code, you were finding the current date twice, which could have given different results on each invocation.
Finally, you might also want to specify CultureInfo.InvariantCulture when you format the date/time - otherwise if the current culture is one which doesn't use a Gregorian calendar by default, you may not get the results you were expecting.
DateTime.Today returns DateTime with all time-related properties set to 0. Use DateTime.Now instead.
Property value
An object that is set to today's date, with the time component set to 00:00:00.
from DateTime.Today Property
Use MM in your format to get month. mm returns minutes. You can check all format specifiers on MSDN: Custom Date and Time Format Strings

want to convert datetime to format like mm/yyyy

I want to grab the datetime object in string form such as "mm/yyyy"
ViewBag.Created = d.item.StartDate.ToString("mm/yyyy");
but I am getting string as 10-2012. Please help me to overcome this issue.
Format for month, should be in MM, mm is for minutes
ViewBag.Created = d.item.StartDate.ToString("MM/yyyy",
CultureInfo.InvariantCulture);
mm is minutes, and / is the culture-specific date separator. It sounds like in the current culture, - is the date separator. I suspect you want MM/yyyy, using the invariant culture, which has / as the separator:
ViewBag.Created = d.item.StartDate.ToString("MM/yyyy",
CultureInfo.InvariantCulture);
Alternatively, you could just quote the slash:
ViewBag.Created = d.item.StartDate.ToString("MM'/'yyyy");
Note that this difference can also change the month and year figures, if the current culture uses a non-Gregorian calendar.
See the MSDN page on custom date and time format specifiers for more details.
Are you certain that you want to fix the format for all cultures though? It's unfortunate that there's no way of saying "give me a culture-appropriate month-and-year format" but you at least need to be aware that it might look odd to some people.
you can use
ViewBag.Created = d.item.StartDate.ToString(#"MM\/yyyy");

DateTime formats C#

I have a string which needs to be converted and validated to a DateTime. The string is in the following format 'dd.mm.yy'
I am trying to convert it to DateTime using the following
string format = "dd.mm.yy";
date = DateTime.ParseExact(current.Substring(aiRule.AiLength), format,
CultureInfo.InvariantCulture);
but unfortunately this fails.
The question is how to convert a string in the format 'dd.mm.yy' to a DateTime ?
Thank you
mm means "minutes". I suspect you want "dd.MM.yy". See MSDN for more information about custom date and time format strings.
(In particular, read the part about the "yy" specifier and how it chooses which century to use. If you can possibly change the input to use a four digit year, that could save you some problems...)
the string format should be like this....
string Format = "dd.MM.yy"
mm is for showing minutes
MM is for showing months..
I hope it will helps you...
As earlier posts has already pointed out, mm means minutes and MM means months. I ran this test snippet and it works as expected:
string format = "dd.MM.yy";
string date = "27.10.11";
DateTime result;
result = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
I'll tell something "heretical". If dd.MM.yy (with 2 or 4 yy) is the format of your local culture, then you could let the DateTime.Parse (not ParseExact!) do its work without setting it to CultureInfo.InvariantCulture, or perhaps setting it to your local culture like new CultureInfo("it-IT").

Categories