String to date conversion in c# as yyyy/mm/dd - c#

I would like convert string content to date format as yyyy/MM/dd HH:mm:ss tt
string date = "2014-11-20 3:21:00 PM";
DateTime date_=System.DateTime.Now;
var result = DateTime.TryParseExact(date, "yyyy-MM-dd HH:mm:ss tt",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date_);
But it returns result doesn't match requirement also TryParse function return false. If time zone is not defined, it will return expected result.

HH specifier is for 24 hour clock which is 00 to 23.
You need to use h specifier instead which represents 1 to 12 in 12 hour clock.
Also you don't need to initialize your out parameter value. Definition will be enough like;
string date = "2014-11-20 3:21:00 PM";
DateTime date_;
var result = DateTime.TryParseExact(date, "yyyy-MM-dd h:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out date_);

The DateTime data type format is always MM/dd/yyyy hh:mm:ss tt (i.e. Date = {11/20/2014 12:00:00 AM}),
If you want to display the value you can change the format by using ToString extention method

Related

DateTime.TryParseExact doesn't seem to be recognizing chinese AM and PM designator characters within a string

I'm trying to parse date and time strings that contain either Chinese AM or PM characters as below. For some reason, the DateTime.TryParse method can get at the correct date and time, but when I try to use the DateTime.TryParseExact method, with what looks to me to be a correct format specifier/mask, the parse fails as shown below where I'm left with a default value for the dateExact variable.
Here's the code:
var dateString = "2018/2/9 下午 03:55:17";
DateTime date = default(DateTime);
DateTime dateExact = default(DateTime);
// this works
DateTime.TryParse(dateString, new CultureInfo("zh-CHS"), DateTimeStyles.None, out date);
// this doesn't work
DateTime.TryParseExact(dateString, "yyyy/M/d tt HH:mm:ss", new CultureInfo("zh-CHS"), DateTimeStyles.None, out dateExact);
Console.WriteLine("Date: " + date);
Console.WriteLine("DateExact: " + dateExact);
And here's the output:
Date: 2/9/2018 3:55:17 PM
DateExact: 1/1/0001 12:00:00 AM
"HH" denotes an hour in 24-hour format. While you're indicating the time is in the PM, 03:55:17 in 24-hour format must be in the AM
The following worked fine for me:
var dateString = "2018/2/9 下午 03:55:17";
DateTime dateExact = default(DateTime);
DateTime.TryParseExact(dateString, "yyyy/M/d tt hh:mm:ss", new System.Globalization.CultureInfo("zh-CHS"), System.Globalization.DateTimeStyles.None, out dateExact);
System.Console.Write(dateExact.ToString());
Note the usage of "hh" instead of "HH"
This has nothing to do with Chinese dates as far as I can tell, the following fails to parse:
var dateString = "2018/2/9 PM 03:55:17";
DateTime dateExact = default(DateTime);
var result = DateTime.TryParseExact(dateString, "yyyy/M/d tt HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateExact);
System.Console.WriteLine(result.ToString());
System.Console.WriteLine(dateExact.ToString());
while changing the string to "2018/2/9 AM 03:55:17" (or "2018/2/9 PM 15:55:17") will cause it to succeed
DateTime.TryParseExact doesn't seem to be recognizing chinese AM and
PM designator characters within a string
Your designator is not the issue as it matches exactly the .NET Framework's definition of a PM Designator for the "zh-CHS" culture:
new CultureInfo("zh-CHS").DateTimeFormat.PMDesignator == "下午" // returns true
Therefore, the problem lies elsewhere in your format string:
Your input has a 12 hour time but you used "HH" which represents the hour as a number from 00 through 23. Use "hh" instead.
DateTime.TryParseExact(dateString, "yyyy/M/d tt hh:mm:ss",
new CultureInfo("zh-CHS"), DateTimeStyles.None, out dateExact);
Date: 09/02/2018 15:55:17
DateExact: 09/02/2018 15:55:17

How to find exact format of a date string?

I need to know exact date format that will perse the string 16-Aug-78 12:00:00 AM. I have tried various string like "ss-MMM-yy hh:mm:ss". Is there any way for finding it to converting to any general format. I am using CultureInfo.InvariantCulture class.
Your string format is wrong. It has to match your string format exactly. You can use dd-MMM-yy hh:mm:ss tt format instead.
Here an example in LINQPad.
string s = "16-Aug-78 12:00:00 AM";
var date = DateTime.ParseExact(s, "dd-MMM-yy hh:mm:ss tt",
CultureInfo.InvariantCulture);
date.Dump();
Custom Date and Time Format Strings
Or, since dd-MMM-yy hh:mm:ss tt is a standart date and time format for InvariantCulture, you can directly DateTime.Parse method like;
string s = "16-Aug-78 12:00:00 AM";
var date = DateTime.Parse(s, CultureInfo.InvariantCulture);
date.Dump();
Here a demonstration.
Is there any way for finding it to converting to any general format?
There is no way to get format of a string except you create your own formatting. Only you can know what is your string format exactly, computer can't.
For example; 01/02/2014 can be 1 February 2014 or 2 January 2014 depends on which custom format you can parse it.
Try as below
var dstring = "16-Aug-78 12:00:00 AM";
DateTime result;
var matchingCulture = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(ci => DateTime.TryParse(dstring, ci, DateTimeStyles.None, out result))
You have wrong format string, you are using ss for day it should be dd. This article Custom Date and Time Format Strings explains what you need for custom format.
Use
"dd-MMM-yy hh:mm:ss tt"
Instead of
"ss-MMM-yy hh:mm:ss"
You can use DateTime.ParseExact to parse the string.
DateTime dt = DateTime.ParseExact("16-Aug-78 12:00:00 AM", "dd-MMM-yy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None);
You can try with DateTime.TryParseExact():
string strDate = "16-Aug-78 12:00:00 AM";
DateTime datDate;
if(DateTime.TryParseExact(strDate , new string[] {"dd-MMM-yy hh:mm:ss tt" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
Console.WriteLine(datDate);
}
else
{
Console.WriteLine("Error in datetime format");
}

Formatting Date and Datetime with SSIS Script Transformation

I have a flat file containing dates like this: 07/07/2003 12:18:20 PM.
The SSIS Transformation Output Column is set to database timestamp [DT_DBTIMESTAMP].
I have the following method:
public string DbDateTime(string input)
{
return DateTime.ParseExact(input, "M/d/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture).ToString();
}
I need an output like this to the database:
2003-07-07 12:18:00.000
However, I keep getting an error:
String was not recognized as a valid DateTime.
The output is set like this:
Row.OuputDateTimeColumn =
Convert.ToDateTime(DbDateTime(Row.InputDateTimeColumn));
I prefer not to use a Derived Column for the conversion.
Problem 1: You are providing invalid custom format for both Month and Date feilds.
you have two fixed digits in your Date String but you are only providing one digit format as below:
"M/d/yyyy h:mm:ss tt"
so you need to Replace this as below:
if your DateString hour format is 00-12
"MM/dd/yyyy hh:mm:ss tt"
if your DateString hour format is 0-12
"MM/dd/yyyy h:mm:ss tt"
Problem 2: You want to return the Date String in custom format of 2003-07-07 12:18:00.000 i assume it is in the format of yyyy-MM-dd h:mm:ss.ffff.
Note: as both Month and Date are same(07) in your example, you need to adjust them accordingly if my assumption is wrong.
so you need to provide the above custom format to the ToString() function in the return statement.
Complete Code:
public string DbDateTime(string input)
{
return DateTime.ParseExact(input, "MM/dd/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture).ToString("yyyy-MM-dd h:mm:ss.fff");
}
Problem 3: while adding the Custom DateFormat to the database you need to first convert it into the DateTime as below:
Row.OuputDateTimeColumn = DateTime.ParseExact(
DbDateTime(Row.InputDateTimeColumn),"yyyy-MM-dd h:mm:ss.fff"
CultureInfo.InvariantCulture);
Your format is wrong. It doesn't match with your input string. Use MM/dd/yyyy h:mm:ss tt format instead. For example;
public string DbDateTime(string input)
{
return DateTime.ParseExact(input,
"MM/dd/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture).
ToString("yyyy-MM-dd h:mm:ss.fff");
}
From 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.
M is for 1 to 12 but MM is for 01 to 12.
d is for 1 to 31 but dd is for 01 to 31.
Also be carefull about your hour forma. h is for 1 to 12, hh is for 01 to 12. If you want to use 24-hour format, you need to use H or HH formats.
For more informations, take a look;
Custom Date and Time Format Strings

How do I convert a string to Date Time in a particular format in C#?

I'm trying to convert "1/7/2014 1:37 PM" (which is a string) to "01/07/2014 13:37" (DateTime format). What would be the best way to do this?
This is what I've got
string dateString = "1/27/2014 1:37 PM";
string format = "MM/dd/yyyy HH:mm";
DateTime dt;
bool temp = DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Console.WriteLine("bool = {0}, dt ={1}", temp, dt);
And my output is
bool = False, dt =1/1/0001 12:00:00 AM
Much thanks.
EDIT:
It's not just for the string I specified. Adding a few more cases - The LHS should get parsed exactly to the RHS
1/7/2014 1:37 PM -> 01/07/2014 13:37
11/27/2014 1:40 AM -> 11/27/2014 01:40
1/12/2014 2:05 PM -> 01/12/2014 14:05
Essentially, the input string does not have leading zeros and time is in 12 hour format and the output should have leading zeros where needed and should display the time in 24 hour format
I've tried giving
string format = "MM/dd/yyyy HH:mm tt";
but that also gives the same wrong output
bool = False, dt =1/1/0001 12:00:00 AM
Four things to change:
You need lowercase h for hours if you use the am/pm designator
You need a single h if the hour can be 1
You need to add tt for the am/pm designator
You need a single M for the month since it's 1
string dateString = "1/27/2014 1:37 PM";
string format = "M/dd/yyyy h:mm tt";
DateTime dt;
bool temp = DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Console.Write("temp: {0} date:{1}", temp, dt); // temp: True date:1/27/2014 1:37:00 PM
See: The "tt" Custom Format Specifier
Update: acccording to your edit:
I also need to convert it back to string in a specific format. It should have leading zeros and time is in 12 hour format and the output should have leading zeros where needed and should display the time in 24 hour format
1/7/2014 1:37 PM -> 01/07/2014 13:37
11/27/2014 1:40 AM -> 11/27/2014 01:40
1/12/2014 2:05 PM -> 01/12/2014 14:05
Then you can use this format string: MM/dd/yyyy HH:mm in DateTime.ToString with CultureInfo.InvariantCulture. Note that i've used uppercase HH for 24h hour format:
string output = dt.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
You need InvariantCulture, otherwise / will be replaced with the actual date-separator of your current culture (f.e. . in germany).
See: The "/" Custom Format Specifier
Maybe you can try like this
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
Console.WriteLine(String.Format("{0:MM/dd/yyyy}", dt));
You should be using
lowercase h rather than H as the time is in 12-, not 24-hour
one h rather than two as you don't have a leading zero on the hour
one M rather than two as you don't have a leading zero on the month
tt to match AM or PM.
Custom Date and Time Format Strings
You can use
Datetime dtDate = DateTime.PareExact(dt,"DateFormat of dt",cultureInfo.InavriantCulture);
Try This...
static void Main(string[] args)
{
string dateString = "1/27/2014 1:37 PM";
string format = "MM/dd/yyyy HH:mm";
DateTime dt2 = Convert.ToDateTime(dateString);
Console.WriteLine(dt2.ToString(format));
Console.ReadLine();
}
This may help:-
DateTime txtmyDate = DateTime.ParseExact(dateString "MM/dd/yyyy hh:mm",
CultureInfo.InvariantCulture);
From DateTime.TryParseExact method
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format, culture-specific
format information, and style. The format of the string representation
must match the specified format exactly.
In your case, it is not.
MM format is for 01 to 12, use M format which is 1 to 12.
HH format is for 00 to 23, use h format instead which is 1 to 12.
Also you are missing tt format which is for AM/PM designator.
string str = "1/27/2014 1:37 PM";
string format = "M/dd/yyyy h:mm tt";
DateTime dt;
bool result = DateTime.TryParseExact(str,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt);
Console.WriteLine(result);
Output will be
True
Here a demonstration.
Your format is wrong. You are missing the AM/PM:
string format = "M/dd/yyyy h:mm tt";
Notice the tt part which is required in order to be able to properly parse the date. Also I would recommend you adding error checking:
string dateString = "1/27/2014 1:37 PM";
string format = "M/dd/yyyy h:mm tt";
DateTime dt;
bool temp = DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
if (temp)
{
Console.WriteLine("bool = {0}, dt = {1:M/dd/yyyy h:mm}", temp, dt);
}
else
{
Console.WriteLine("Unable to parse date: {0}", dateString);
}

C# DateTime Conversion from yyyy-MM-ddTHH:mm:ss to dd MMM yyyy

How to convert "yyyy-MM-ddTHH:mm:ss" into "dd MMM yyyy" format? For Instance, i want to convert 2013-04-16 05:30:05 into 16 April 2013. What is the correct method to achieve this?
First ParseExact then do ToString (I assume that you have string object, if you have DateTime object, skip first line)
var dateTime = DateTime.ParseExact(yourDateString, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
var yourNewString = dateTime.ToString("dd MMM yyyy");
Note that representation of DateTime you see in debugger is dependant on your current culture.
First, a DateTime has no format. But if you've already a string that represents a DateTime with the format yyyy-MM-ddTHH:mm:ss and you want to convert it to a string-date with format dd MMM yyyy you need to parse it to DateTime first.
Therefore use DateTime.ParseExact:
DateTime dt = DateTime.ParseExact("2013-04-16 05:30:05", "yyyy-MM-dd HH:mm:ss", null);
Now you can use DateTime.ToString:
string result = dt.ToString("dd MMM yyyy");
Note that you need to pass a different CultureInfo object to ParseExact/ToString if you want to parse with another DateTimeFormat than your current (f.e. force english month names instead of german: dt.ToString("dd MMM yyyy", CultureInfo.InvariantCulture)).
As others mentioned, a DateTime has no format. To parse a string literal to a Date you need to call DateTime.Parse (if the string is in a culture-specific format) or DateTime.ParseExact if you need to pass a format string.
The format can be a custom format like yyyy-MM-dd HH:mm:ss or one of the standard format strings, eg. s for yyyy-MM-ddTHH:mm:ss.
2013-04-16 05:30:05 it not in one of the standard formats, so you have to parse by passing a custom format string:
var dt = DateTime.ParseExact("2013-04-16 05:30:05", "yyyy-MM-dd HH:mm:ss", null);
On the other hand, yyyy-MM-ddTHH:mm:ss is the s standard format so you can just write:
var dt = DateTime.ParseExact("2013-04-16T05:30:05", "s", null);

Categories

Resources