Convert String To Date - c#

I want to convert dd/MM/yyyy to MM/dd/yyyy.
My code:
string g = "20-1-1999";
DateTime dt = DateTime.ParseExact(g, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Error Message:
String was not recognized as a valid DateTime.

You have to give single M for month in format string. You can read more about format specifier MM, here and M here. You also need to using - as separator instead of /
DateTime.ParseExact(g, "dd-M-yyyy", CultureInfo.InvariantCulture);
If you expect day single digit you would give single d for day too.
DateTime.ParseExact(g, "d-M-yyyy", CultureInfo.InvariantCulture);
The "MM" Custom Format Specifier
The "MM" custom format specifier represents the month as a number from
01 through 12 (or from 1 through 13 for calendars that have 13
months). A single-digit month is formatted with a leading zero, MSDN
The "M" Custom Format Specifier
The "M" custom format specifier represents the month as a number from
1 through 12 (or from 1 through 13 for calendars that have 13 months).
A single-digit month is formatted without a leading zero, MSDN.

your format should be dd-M-yyyy
DateTime dt = DateTime.ParseExact(g, "dd-M-yyyy", CultureInfo.InvariantCulture);
var result = dt.ToString("MM/dd/yyyy");

Related

Error parsing Datetime format

I am trying to parse two string values into DateTime.
DateTime processStartTime = DateTime.ParseExact(currentDateTime.Date.ToString("dd-MM-yyyy") + " " + "00:00", "dd-MM-yyyy hh:mm", System.Threading.Thread.CurrentThread.CurrentCulture);
DateTime processEndTime = DateTime.ParseExact(currentDateTime.Date.ToString("dd-MM-yyyy") + " " + "13:00", "dd-MM-yyyy hh:mm", System.Threading.Thread.CurrentThread.CurrentCulture);
The first statement works fine, but the second statement fails with exception-
String was not recognized as a valid DateTime
What I am doing wrong?
You have to use HH:mm instead of hh:mm for 24h format
The "hh" custom format specifier:
represents the hour as a number from 01 through 12; that is, the hour
is represented by a 12-hour clock that counts the whole hours since
midnight or noon.
The "HH" custom format specifier:
The "HH" custom format specifier (plus any number of additional "H"
specifiers) represents the hour as a number from 00 through 23; that
is, the hour is represented by a zero-based 24-hour clock that counts
the hours since midnight. A single-digit hour is formatted with a
leading zero.
Are you really converting a DateTime object to a string and then convert it back to a DateTime? Otherwise you could just write:
var startTime = currentDateTime.Date;
var endTime = currentDateTime.Date.AddHours(13);

Datetime.parseExact gives (1-9) day's value with single digit, without 0

I have this code, it gives day's value as 1,2,3 .. instead of 01,02,03..
(DateTime.ParseExact("20160416", "yyyyMMdd", CultureInfo.InvariantCulture))
gives: 4/16/2016 12:00:00 AM.
I need 04/16/2016 12:00:00 AM
I have tried different cultures but nothing worked.
DateTime doesn't store any formatting information, it's just a structure representing a date and time. ParseExact is parsing your date string correctly.
If you want it formatted, you supply a format to DateTime.ToString, for example:
var formattedDate = dateTime.ToString("MM/dd/yyyy hh:mm:ss tt");
See this fiddle.
DateTime.ParseExact returns DateTime which doesn't have any implicit format. This "format" concept only applies when you get it's textual (a.k.a. string) representation.
You didn't told use how and where you see this 4/16/2016 12:00:00 AM string but if you wanna get days part with leading zero, you can use The dd format specifier with a proper culture (for calendar and time designators).
The dd custom format string represents the day of the month as a
number from 01 through 31. A single-digit day is formatted with a
leading zero.
DateTime dt = DateTime.ParseExact("20160416", "yyyyMMdd", CultureInfo.InvariantCulture);
string str = dt.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
// 04/16/2016 12:00:00 AM

Unable to parse DateTime with a custom format

After reading some other similar questions and trying their suggestions, I'm still unable to get my time to parse into a DateTime-
string time1 = File.ReadAllText(#"C:\Reminders\Reminder1Time.txt");
DateTime dt1 = DateTime.ParseExact(time1, "hh:mm:tt", CultureInfo.InvariantCulture);
dateTimePicker1.Value = dt1;
time1 is a string value of 9:00 AM Other questions have mentioned to use ParseExact to specify a custom format, but it's still not parsing.
The error I get thrown is on the second line
String was not recognized as a valid DateTime.
How would I get the dateTimePicker1 to display the value from the time1 string?
Looks like a stray colon and an extra h if you are expecting a 12 hour clock 1-12 without a leading zero and the AM PM marker with whitespace.
Try: h:mm tt
All of the formatting options are buried in the documentation, here.
var datefromFile = File.ReadAllText(FILELOCATION);
var format = "dd-MM-yyy hh:mm:ss,fff";
var formattedDateTime = DateTime.ParseExact(dateFromFile, format, CultureInfo.InvariantCulture);
Make your format Explicit, remember dd for date capital MM for month and yyyy for year. hh for hour mm for minutes and ss for seconds.
MSDN Formats:
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

String was not recognized as a valid DateTime on DateTime.ParseExact

I know there is a lot of asked question here about DateTime but I saw them all already and seems not to find the right solution for my case.
Here is my code:
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "dd/MM/yyyy", new CultureInfo("en-us");
This is throwing me an Exception.
Here is the value of the variables:
string partialDate = "1/22";
string dtfi.DateSeparator = "/";
int _baseDate = 2004;
You should use format "m/dd/yyyy" because datestring becomes 1/22/2004
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "m/dd/yyyy", new CultureInfo("en-us"));
Unfortunately, both answers are wrong.
So, we all agree your result string will be "1/22/2004". Before looking which formats exactly matches your characters, let's look at your string is a standard date and time format for en-US culture or not.
DateTime.Parse("1/22/2004",
CultureInfo.GetCultureInfo("en-US")) // 22 January 2004 00:00:00
BANG!
We have a DateTime perfectly. But what if our string wouldn't be a standard date and time format for en-US culture? Then we can specify our format with DateTime.TryParseExact method. Let's look at which formats we can use to parsing our string.
1 matches with "M" custom format specifier which is from 1 to 12 and single-digit month is formatted without a leading zero.
/ is a DateSeparator and we can use it the same in our format because en-US culture has / as a DateSeparator already. Remember, "/" custom format specifier has a special meaning of replace me with current culture or supplied culture date separator
22 matches with "dd" custom format string which is from 01 to 31 and single-digit days is formatted with a leading zero. Remember, you can also use d format specifier in such a case but using wider formats is recommended.
2004 matches with "yyyy" custom format specifier which represents the year with a four digits.
So, the right format will be M/dd/yyyy in result.
string s = "1/22/2004";
DateTime dt;
if(DateTime.TryParseExact(s, "M/dd/yyyy", CultureInfo.GetCultureInfo("en-US"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt); // 22 January 2004 00:00:00
}
You are referring to wrong format, so obviously it will throw exception. Below is what you are doing
string partialDate = "1/22";
string dtfi.DateSeparator = "/";
int _baseDate = 2004;
string ex = partialDate + dtfi.DateSeparator + _baseDate.ToString();
which gives you 1/22/2014 i.e., MM/dd/yyyy
and in code you are referring to
return DateTime.ParseExact(partialDate + dtfi.DateSeparator + _baseDate.ToString(), "dd/MM/yyyy", new CultureInfo("en-us");
Try using correct Format, to get the right result.

How can I get this DateTime format in .NET

I'm trying to format some DateTime into this W3C DateTime format :-
Complete date plus hours and minutes:
eg. YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
I originally had this...
var myDateTime = someDateTime.ToString("s",
System.Globalization.CultureInfo.InvariantCulture);
But that results in a string of :
2011-08-31T08:46:00
Can anyone help?
You want "o":
var myDateTime = someDateTime.ToString("o",
System.Globalization.CultureInfo.InvariantCulture);
Use the following:
yourDateTime.ToString( "yyyy-MM-ddTHH:mmK", CultureInfo.InvariantCulture );
Here is more than you'll ever want to know on DateTime formats:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
I believe you want
"yyyy-MM-ddTHH:mmK"
Note:
HH rather than hh to be 24 hour
K to specify the time zone; this relies on the DateTime.Kind being UTC or local; unspecified will end up with an empty string
You should also use CultureInfo.InvariantCulture to make sure no funky culture information is used. (You could quote the - and : as an alternative, but I'd use the invariant culture to make sure.)
You can format it like this:
someDateTime.ToString("yyyy-MM-dd");
Here's the documentation of the 'standard' supported datetime format strings:
http://msdn.microsoft.com/en-us/library/az4se3k1(v=VS.100).aspx
someDateTime.ToUniversalTime().ToString("u");
Will get you pretty close => '2011-09-02 10:22:48Z'. If that isn't good enough, then you can create a custom format string that includes the "T" (see 'Custom Date and Time Format Strings').

Categories