DateTime.Now.ToString("MM/DD/YYYY") contains incorrect month - c#

So I have been adding a DateTime.Now.ToString("MM/DD/YYYY") to a List (along with a bunch of other data) and the later writing these lists to individual rows in an Excel workbook.
This all works great (it's something I do regularly), except, the month. I have tried exporting it three times and each time I get a different month;
the first time 56/26-17,
the second 2/26/2017,
and the third 14/26/2017....

Use this instead:
DateTime.Now.ToString("MM/dd/yyyy")
"MM" for month. "dd" for days. "yyyy" for year.
"MM/DD/YYYY" is wrong format:
Console.WriteLine(DateTime.Now.ToString("MM/DD/YYYY")) // prints "06/DD/YYYY"

DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
As already answered you need to have format specifier for day and year in small letters but as an add on you should also specify the culture variable to make sure that final output contains "/" between date parts. Without this culture parameter "/" could be replace by the date separator of the culture of system where code is running like "-".

Related

Is there a specific date format that needs to be inserted in Sqlite db DateTime column?

I'm trying to insert a datetime value into a sqlite table, however the value that's inserted is
"YYYY-01-DD08:01:SS"
{ "NextSyncDate", task.NextSyncDate.ToString("YYYY-MM-DD HH:MM:SS") }
Is there a way to insert am/pm as well in sqlite table's datetime field? Thanks!
This has NOTHING to do with SqlLite and is a basic C# question.
The following is the string you execute to get the timestamp:
.ToString("YYYY-MM-DD HH:MM:SS")
This is totally C#. It also is totally incorrect.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
explains all components you can use and guess what - the first one (YYYY) is already not on the list. The C# version is "yyyy" - small. And as some are there in MM and mm (minute and Month) - you basically create garbage.
Hint: next time use debugging. GRAB THE STRING - then it would be obvious that the output of that ToString makes no sense.
Not all letters should be uppercase inside ToString. Try like:
ToString("yyyy-MM-dd HH:mm:ss")
capital MM is month where as lowercase mm is minutes. Capital HH is 24 hours format, where as if you write lowercase hh is 12 hours format

Get current date in personalized format in c#

I would like to know if there is a way to get the current date in the following format :
YYYY.MM.DD
I know that I can get the current date, and then manipulate it to get the desired format, but I was wondering if there is a pattern solution to specify my own format and so directly getting a string like this :
"2014.06.10"
string dateFormatted = DateTime.Today.ToString("yyyy.MM.dd");
You can use the string.Format() method and reference this link http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
The {#} represents the argument being passed and the {#:yyyy} is a way of formatting to grab just the year in format of yyyy. Same for MM and dd. Worth noting is that mm is minutes and MM is months which may be confusing as day and year are also lower case.
string.Format("{0:yyyy}.{0:MM}.{0:dd}", DateTime.Now);

format datetime based on users culture

How can I format the date and time depending on the users region settings in an ASP.NET-MVC application without worrying about the order of the date?
For example, I want to have:
the day with a leading zero (dd);
month abbreviated three-letter form (MMM);
full year (yyyy);
the time just the hours and minutes both with leading zeros (HH:mm);
depending on if the user is from USA show AM/PM after the time;
Every country displays the date in a different order. USA displays first the month than days than years (MMM/dd/yyyy). In China first the year than month than day (yyyy-MMM-dd) (IIRC). And in Europe most countries display the date in this format: dd-MMM-yyyy.
And then not to mention the slashes/dashes used to separate the month, days and years from each other in every country.
This of course can be done with an endless if/else or switch statement, but isn't there a more elegant way to do this?
EDIT this is the best I came up with:
var cltr = System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime.Now.ToString(cltr.DateTimeFormat.ShortDatePattern + " " + cltr.DateTimeFormat.ShortTimePattern)
It displays the date in numbers only. How would I change that in short month notation but not changing the order and the separators etc?
You can get the culture currently used by the user with CurrentCulture and CurrentCultureInfo.
For more details, see: http://msdn.microsoft.com/en-us/library/bz9tc508.aspx
I think you are talking about formatting issue. Once you have your DateTime object, then you can display it as you want. You have to specify new CultureInfo("en-US") as IFormatProvider in the DateTime.ToString() method if you want to show the datetime as US format.

convert string in unknown format to date in c#

I have searched stackoverflow for an answer but no luck. I am developing a windows application and I have some strings in different date formats,
eg.
dd/MM/yyyy
MM/dd/yyyy
MM-dd-yyyy
dd-MM-yyyy
dd/MM/yyyy hh:mm::ss
MM/dd/yyyy hh:mm::ss
etc...
But I need to convert in to a common format - dd/MM/yyyy. The application can run in any windows machines in different culture.
What is the correct way to do it?
EDIT: One more thing I may not know what the format of incoming string.
Thanks in advance.
Use DateTime.ParseExact with the different patterns as formats.
If after parsing you really need to use a string representation, use the ToString method of the DateTime with the explicit format that you're interested in (so that it is culture-invariant). It's better however to keep the DateTime because this is format-agnostic.
You could distinguish between those formats that use different separators (i.e. "/" vs "-"). But how would you know if date such as 10/11/2010 represents 10th of November or 11th of October? If one number is not bigger than 12, there is no reliable way to do this without knowing an exact format.
As others have pointed out, if you do know the exact format, then you can use DateTime.ParseExact.
If you are processing some import file with a lot of dates in the same unknown format, you could try different formats and hope there is exactly one that doesn't give format errors.
Or to put it another way: split the "dates" into three numbers and check the range of values for each of those numbers. Values > 1900 will be years. If you find values from 1 to 31, those will be days.
Values from 1 to 12 might be months, but could also be days. Try and identify each of the parts.
The best way is to ask the supplier of those dates for the format.
To run this program on different culture, i think you should creat a function to indentify the culture of this string format and then use Datetime.Parse

DateTime problem when day <= 12

I've looked around a lot and short of writing a horrible chunk of code to manipulate the string, I'd like to ask if anyone knows a nice way of sorting it:
I have a bunch of date strings in cells that I'm pulling out such as:
03/05/2011
27/05/2011
31/05/2011
03/05/2011
09/05/2011
31/05/2011
etc.
While I'm reading any entires where the day can be construed as a month - i.e. entries 1, 4 and 5 above - it gets put in as a DateTime with the day and month swapped.
For example, 03/05/2011 gets read in as a DateTime "05/03/2011 00:00:00"
The others are all read and nicely provide me with a simple string of "27/05/2011".
I'm getting this info from Excel, using
((Excel.Range)worksheet.Cells[rowCount, 3]).Value.ToString()
If I try Value2 as with my other lines, it reads those odd dates as things like "40607" but again, will read the other dates normally.
If you use the DateTime.ParseExact function to convert a string to a DateTime object, you can specify the specific format used by your dates (which looks like "day/month/year") without having to do any string manipulation whatsoever.
Example:
var dateString = "03/05/2011";
var format = "dd/MM/yyyy";
var date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
More information on custom Date and Time format strings can be found here.
EDIT: Try using the DateTime.FromOADate method to convert the value returned by the Range.Value2 property to a DateTime object, e.g. something like this:
var dateTime = DateTime.FromOADate(((Excel.Range)worksheet.Cells[rowCount, 3]).Value2);
DateTime.ParseExact Method converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information.
The format of the string representation must match the specified format exactly.
String dateString = "15/06/2008";
String format = "dd/MM/yyyy";
DateTime result =
DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
That sounds like a localization problem. Try setting your locale implicititly. For example in WPF application it's something like:
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US");
I have a bunch of date strings in cells that I'm pulling out such as:
No, you don't. You have a mix of strings that look like dates and dates that look like strings. This is an Excel issue, not a C# issue.
Not sure if you are creating the spreadsheet, or if you are getting it from somewhere else. But it the problem is that Excel attempt to parse text as it is entered in the cell. In this case, it is making some wrong decisions about the dates it finds.
If you enter a date like "03/05/2011", Excel will (incorrectly) parse it as March 5th, 2011, and store that as a numeric date code (40607). It then applies a date formatting to the cell (it uses m/d/yyyy on my machine).
If you enter a date like "31/05/2011", Excel can't parse it as a date, and it stores it as text.
To prove this, select the cells and go to Edit > Clear > Formats. All the "bad dates" will just show as numbers, all the rest will stay looking like dates.
You have a few choices:
Fix the data before its entered into Excel (prepend everything with a ' so its all entered as text, or make sure to create the spreadsheet on a machine that has the right date settings.)
Don't use the .Value.ToString() from Excel, just use .Text. This will ignore the bad parsing that Excel did, and should give you a consistent text value (from both types) that you can ParseExact with C#, per the other answers.
(2) is a lot easier, and if the spreadsheets already exist, may be your only choice.
The problem is because your Dates are being read as american culture or similar.
If you use the following you can specify the format you expect your dates to be in:use
DateTime result;
if(DateTime.TryParseExact("dd/MM/yyyy", out result))
{
// Got an English date
}

Categories

Resources