Convert s string to specific DateTime format with timezone - C# - c#

I am trying this code (c#):
string input1 = "2009-11-22 01:01:05 +1:30"
string input2 = "2009-11-22 01:01:05"
DateTime date1 = new DateTime();
DateTime date2 = new DateTime();
string format = "yyyy-MM-dd hh:mm:ss [z]"
DateTime orgDate1 = DateTime.ParseExact(input1, format, null);
DateTime orgDate2 = DateTime.ParseExact(input2, format, null);
The purposes are:
recognize the term "[z]" as optional parameter so both input1 and input2 will be parsed correctly.
To get valid DateTime parsed values in orgDate1 and orgDate2.
The problem:
I don't manage to get parsed values, even if ignore the optional requirement:
string input1 = "2009-11-22 01:01:05 +1:30"
DateTime date1 = new DateTime();
string format = "yyyy-MM-dd hh:mm:ss zzz"
DateTime orgDate1 = DateTime.ParseExact(input1, format, null);
I tried many options, like:
DateTime.ParseExact("2009-11-22 00:00:00 1", "yyyy-MM-dd hh:mm:ss z",null)
DateTime.ParseExact("2009-11-22 00:00:00 1", "yyyy-MM-dd hh:mm:ss Z",null)
But always get formatException.
Only this code works:
DateTime.ParseExact("2009-11-22 00:00:00Z", "yyyy-MM-dd hh:mm:ssZ",null)
But it returns the exact UTC time zone while I need to get it as parameter.
all is described above

Ok, after several trials I find that following code works:
DateTime.ParseExact("2009-11-22 00:00:00+1", "yyyy-MM-dd hh:mm:ss z",null)
So remain the other Q - how can I define the format with optional timezone, such that both "2009-11-22 00:00:00+1" and "2009-11-22 00:00:00" will be parsed properly?

Related

Error “String was not recognized as a valid DateTime” [duplicate]

This question already has answers here:
unable to parse a string of this format "1/29/2020 12:00:00 AM" into a valid DateTime
(2 answers)
Closed 2 years ago.
I have these 2 string values:
Test1 = "2020-01-29T00:00:00Z"
Test2 = "29/01/2020 00:00:00"
and I am doing this comparison:
(DateTime.ParseExact(Test2.ToString(), "dd/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).ToString("yyyy'-'MM'-'dd'T'00':'00':'00'Z'") != (DateTime.ParseExact(Test1["ProjectDateSinged"].ToString(), "yyyy'-'MM'-'dd'T'00':'00':'00'Z'", CultureInfo.InvariantCulture)).ToString()))
but this will raise the following exception:
Error “String was not recognized as a valid DateTime”
Could anyone find what is wrong with my code?
Expanding my comment into answer, you should update your format string a little bit. For Test2 you should use dd/MM/yyyy hh:mm:ss format.
According to Custom date and time format strings MM is used for month number from 01 to 12, M from 1 to 12. You have 01 month number, so MM should be used.
There is also no AM/PM representation in your date, so tt is not needed as well
Them you'll be able to parse Test2 into the date.
var Test2 = "29/01/2020 00:00:00";
var result = DateTime.ParseExact(Test2, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
For the Test1 you can use yyyy-MM-ddThh:mm:ssK (parse the date including time zone information) or yyyy-MM-ddThh:mm:ss'Z' without time zone information.
To compare the dates you don't need to convert them back to string. You can simply get the date component using Date property of DateTime struct. The code below returns true
var result = DateTime.ParseExact(Test1, "yyyy-MM-ddThh:mm:ss'Z'", CultureInfo.InvariantCulture).Date ==
DateTime.ParseExact(Test2, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture).Date;
as well as this, by comparing two DateTime instances only
var result = DateTime.ParseExact(Test1, "yyyy-MM-ddThh:mm:ss'Z'", CultureInfo.InvariantCulture) ==
DateTime.ParseExact(Test2, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
string Test1 = "2020-01-29T00:00:00Z";
string Test2 = "29/01/2020 00:00:00";
DateTime dt = Convert.ToDateTime(Test1, CultureInfo.InvariantCulture);
MessageBox.Show("" + dt.ToString("yyyy-MM-ddT00:00:00Z"));
Used this code then successfully work
By looking at your examples, the formats looks below.. You can write a generalized method by specifying formats. something like below -
private static DateTime ParseDate(string providedDate)
{
DateTime validDate;
string[] formats = { "dd/MM/yyyy hh:mm:ss", "yyyy-MM-dd'T'hh:mm:ss'Z'" };
var dateFormatIsValid = DateTime.TryParseExact(
providedDate,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out validDate);
return dateFormatIsValid ? validDate : DateTime.MinValue;
}
And call this method to parse the string
var test1 = ParseDate("2020-01-29T00:00:00Z");
var test2 = ParseDate("29/01/2020 00:00:00");
Console.WriteLine(test1 == test2); // result TRUE

DateTime format conversion mm/dd/yyyy to yyyy/mm/dd

Can someone please let me know how do I convert this datetime format into yyyyMMdd
2/28/2017 12:02:04 AM
At the output I should get 20170228
Any advice on this?
If you already have the DateTime as an object
string formattedDate = date.ToString("yyyyMMdd");
If you need to parse the value first.
string dateValue = "2/28/2017 12:02:04 AM";
string format = "M/d/yyyy hh:mm:ss tt";
DateTime dateTime = DateTime.ParseExact(dateValue, format,
System.Globalization.CultureInfo.InvariantCulture);
For reference you can find a breakdown of the Custom Date and Time Format Strings
You need to specify the format of the date.
If you want it for the current time you can try like this :
string dtime = DateTime.Now.ToString("yyyy/MM/dd");
This is the solution I have come up with for you:
string format = "M/d/yyyy hh:mm:ss tt";
string dateString = "2/28/2017 12:02:04 AM";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(dateString, format, provider);
string output = date.ToString("yyyyMMdd");
If you're using C# 6 or later (VS2015), you can format DateTime objects easily by using string interpolation using a custom format string. The custom format string that you're looking for is "yyyyMMdd".
// create your preferred date and time in a new DateTime struct
DateTime yourDateTime = new DateTime(2017, 2, 28, 0, 2, 4);
// format yourDateTime as a string
string yourFormattedDateTime = $"{yourDateTime:yyyyMMdd}";
You can read more about interpolated strings at https://msdn.microsoft.com/en-us/library/dn961160.aspx, and, as previously mentioned by #Adam Carr, you can find more information on custom date and time format strings at https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Format datetime from string "20151210T11:25:11123"

I have string format "20151210T11:25:11123", can't convert to type DateTime in C# help me?
string date = "20151210T11:25:11123";
DateTime datea = DateTime.ParseExact(date, "dd/MM/yyyy hh:mm tt", CultureInfo.InvariantCulture);
You are using a time of 20151210T11:25:11123 but telling it to parse it as if it were formatted as dd/MM/yyyy hh:mm tt. The format does not match the string, so you get a FormatException. You need to provide a format that matches the string you have. It isn't clear to me what the last 5 digits are but a format like yyyyMMddThh:mm:ssfff will parse the string as 12/10/2015 11:25:11 AM. You may need to adjust the last part of the format to match whatever is actually encoded there in your string.
string date = "20151210T11:25:11123";
DateTime datea = DateTime.ParseExact(date, "yyyyMMddThh:mm:ssfff", CultureInfo.InvariantCulture)
Console.WriteLine(datea); // 12/10/2015 11:25:11 AM
with value datetime string ="20160121T13:26:24090"
code error :
DateTime datea = DateTime.ParseExact(date, "yyyyMMddThh:mm:ssfff", CultureInfo.InvariantCulture)
Console.WriteLine(datea); // 12/10/2015 11:25:11 AM

String was not recognized as a valid DateTime. Throws an Exception

I'm trying to convert current date to a specified format.
DateTime date = DateTime.ParseExact(DateTime.Now.ToString(), "yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
I'm receiving the following exception.
String was not recognized as a valid DateTime.
My local TimeZone is (UTC+10:00)Melbourne.
What am I doing wrong here?
Your code (even if it worked), would do nothing. It would simply serialize and deserialize the date. I believe you're looking for this:
string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
It doesn't work because DateTime.Now.ToString() is giving a string like (I happen to be in the same timezone, and presumably have the same culture as you):
14/01/2016 3:54:01 PM
Which is of the format:
dd/MM/yyyy h:mm:ss tt
Which does not match the format you're using: yyyy-MM-dd HH:mm:ss.fff
Try this:
string fm = "yyyy-MM-dd HH:mm:ss.fff";
string str = DateTime.Now.ToString(fm, CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(str, fm, CultureInfo.InvariantCulture);
EDIT:
A better way to achieve the date in the format would be like
DateTime now = DateTime.Now;
CultureInfo culture = new CultureInfo("en-AU"); //Melbourne
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
IDEONE DEMO

I am getting Error as String was not recognized as a valid DateTime

private string format = "dd/MM/yyyy HH:mm:ss";
DateTime fromdate = DateTime.ParseExact(GetFromScanDateTextBox.Text, format, CultureInfo.InvariantCulture);
I am getting error when executing this line string was not recognized as a Valid Date Time.
I have tried this also but it not works
DateTime fromdate = DateTime.ParseExact(GetFromScanDateTextBox.Text, format,null);
Your format string must be "d/M/yyyy", take a look at this.
Basically
MM : The month, from 01 through 12.
while
M : The month, from 1 through 12.
The same for the day part.
You are telling DateTime.ParseExact that you are expecting a string with format dd/MM/yyyy HH:mm:ss but you are giving it a string with format d/M/yyyy.
You need to change your format to just d/M/yyyy.
Also I suggest using DateTime.TryParseExact to verify the validity of your string instead of using exceptions.
var okay = DateTime.TryParseExact(
input,
new[] { "dd/MM/yyyy HH:mm:ss", "d/M/yyyy" },
new CultureInfo("en-GB"),
DateTimeStyles.None,
out dateTime);
If your input string is liable to change, TryParseExact allows you to define multiple formats as shown above, or alternatively, if it is always going to be with your current culture, just do DateTime.TryParse and do away with defining the format.
var okay = DateTime.TryParse(input, out dateTime);
If your format is always month/date/year and particularly in this case(if your date is 3rd Sept 2013) you can use:
string format = "MM/dd/yyyy";
string dateTime = "9/3/2013";
dateTime = (dateTime.Split('/')[0].Length == 1 ? "0" + dateTime.Split('/')[0] : dateTime.Split('/')[0]) + "/" + (dateTime.Split('/')[1].Length == 1 ? "0" + dateTime.Split('/')[1] : dateTime.Split('/')[1]) + "/" + dateTime.Split('/')[2];
DateTime fromdate = DateTime.ParseExact(dateTime, format, CultureInfo.InvariantCulture);
Do not provide the HH:MM:SS part in the format part
string format = "dd/MM/yyyy";
DateTime fromdate = DateTime.ParseExact(test.Text, format, CultureInfo.InvariantCulture);

Categories

Resources