Convert unusual string to DateTime w/out foreach - c#

Update My Solution:
var rowsToAdd = (from t in dtEntry.AsEnumerable().Cast<DataRow>()
let startDate = (
t.Field<string>("StartDate").Length > 0)
? DateTime.Parse(t.Field<string>("StartDate").Split(new Char [] {'('})[0], CultureInfo.InvariantCulture)
: DateTime.Today.AddMonths(-3)
where startDate > filterDate
select t);
Original Question:
I get a DateTime string from an external API that looks like this:
10/14/2014 8:30 AM (America/Los Angeles)
I have all the data in a datatable called dtEntry which I'm using below.
None of the built-in c# DateTime conversion functions seem to work. They all result in format exeptions. Does anyone know how I could do this? The other catch is that I'm using LINQ (see below).
DataRow[] rows = (from t in dtEntry.AsEnumerable().Cast<DataRow>()
let startDate = (
t.Field<string>("StartDate").Length > 0)
? DateTime.Parse(t.Field<string>("StartDate"))
: DateTime.Today.AddMonths(-3)
where startDate > filterDate
select t).ToArray();
Any ideas? I've got the ternary operator in there because I need to handle empty strings as well.

You can split your string based on space and then Take(3) elements from the result array, Join them back using string.Join and then use DateTime.ParseExact or DateTime.TryParseExact like:
string str = "10/14/2014 8:30 AM (America/Los Angeles)";
string newStr = string.Join(" ", str.Split().Take(3));
DateTime parsingDateTime;
if (!DateTime.TryParseExact(newStr, "M/d/yyyy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None,
out parsingDateTime))
{
//invalid datetime
}
EDIT: You have to ignore (America/Los Angeles) part of string, otherwise there is no way for parsing using such string. You can find TimeZone for Region and then create DateTime for that parameter. See this: Get timezone by Country and Region

The accepted answer does not take into account the time zone part. My assumption here is the time zone is a standard time zone identifier which can be translated from the Unicode.org site. And based off this other SO Answer (.NET TimeZoneInfo from Olson time zone) which provides a helper method from the Unicode.org site, you can then parse the api time to your time:
string apiTime = "10/14/2014 8:30 AM (America/Los Angeles)";
int timeZoneStart = apiTime.IndexOf('(');
string timeZonePart = apiTime.Substring(timeZoneStart)
.Replace("(", string.Empty) // remove parenthesis
.Replace(")", string.Empty) // remove parenthesis
.Trim() // clear any other whitespace
.Replace(" ", "_"); // standard tz uses underscores for spaces
// (America/Los Angeles) will become America/Los_Angeles
string datePart = apiTime.Substring(0, timeZoneStart).Trim();
DateTime apiDate = DateTime.Parse(datePart);
TimeZoneInfo tzi = OlsonTimeZoneToTimeZoneInfo(timeZonePart);
DateTime apiDateTimeConverted = TimeZoneInfo.ConvertTime(apiDate, tzi);
The method above, OlsonTimeZoneToTimeZoneInfo, is from the SO answer linked above.

Related

Not getting correct date from DateTime in c#

I need only date in the yyyy-MM-dd format, but I'm getting (20/03/2018 0:00:00) date in wrong format.
var d = Convert.ToDateTime("2018-03-20T00:00:00.000",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
var finaldate = DateTime.TryParseExact(d, "yyyy-MM-dd", null);
Output i am getting --20/03/2018 0:00:00
expected -- 2018-03-20
I will try to explain what the others meant when they wrote "DateTime has no format".
DateTime is a C# type that has properties for year, month, day, etc.
If you want to print a DateTime, you first have to convert it to a string. During this conversion, you can define the output format.
Also, if you parse a string into a DateTime, you can define the expected input format.
This is what the "Standard Date and Time Format Strings" / "Custom Date and Time Format Strings" are for.
An example:
string d = Convert.ToDateTime("2018-03-20T00:00:00.000",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
DateTime finaldate = DateTime.TryParseExact(d, "yyyy-MM-dd", null); // not a string!
int year = finadate.Year; // year == 2018 (a number!)
int month = finaldate.Month; // month == 3 (a number again!)
string isoFormat = finaldate.ToString("yyyy-MM-dd"); // isoFormat == "2018-03-20"
string usFormat = finaldate.ToString("MM/dd/yyyy"); // usFormat == "03/20/2018"
// and so on...
Note that if you just call ToString() without specifying any format, the result will depend on the culture of the current thread (probably "en-Us" judging from the output you have shown). See DateTime.ToString Method.
DateTime always returns DateTime object with the time part.
To get expected output, you have to return string eg. DateTime.Now.ToString("dd-MM-yyyy")

ParseExact string to DateTime

I try to parse my string to datetime, but I get a FormatException.
string date = "27.02.2017 13:03:16 Uhr";
action.Date =
DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss",CultureInfo.InvariantCulture);
Does somebody has any idea?
You have to escape Uhr suffix:
string date = "27.02.2017 13:03:16 Uhr";
action.Date = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss 'Uhr'",
CultureInfo.InvariantCulture);
The problem is the "Uhr" at the end of the input. If you specify your format like this, the input must match the format.
After some people add "Uhr" and some people don't, I recommend to extract the relevant part using a regex.
using System.Text.RegularExpressions;
Match m = Regex.Match( #"/([\d]{2}\.[\d]{2}\.[\d]{4} +[\d]{2}\:[\d]{2}\:[\d]{2})/", date);
if (m != null)
date = m.Groups[0].Value;
else
// Something wrong with the input here
And then (unless m is null) you can use this string as a valid input for your ParseExact-part in most cases. But be aware that the regex does not perform any range-checks, so an input like Montag, 99.99.9999 99:99:99 Uhr would lead to the date string 99.99.9999 99:99:99 which matches the regex, but is not a valid DateTime anyway.

DateTime Format Handling

I have a program that has synchronization. That means I need to save the last synchronization date and check if it needs to be synchronized.
So, I have this:
IS.SaveContactsRetrieveDate(DateTime.Now.ToString("dd.MM.yyyy"));
Saving a date to Isolated Storage.
Then, when I call IF:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
if (contactsRetriveDate == "" || DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate)) == 1)
{
MessageBox.SHow("");
}
The problem is that when user changes the region code fails here:
DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate))
With incorrect input error.
I understand that Latvian format is dd.MM.yyyy and USA MM/dd/yyyy - but I can't find a solution...
I need all datetime parsed in one format, so I could add days, weeks and compare date.
You should serialize and deserialize your date in a culture-independent manner (where "d" is the "Short date pattern" of the Standard Date and Time Format Strings):
var s = DateTime.Now.ToString("d", CultureInfo.InvariantCulture);
var d = DateTime.Parse(s, CultureInfo.InvariantCulture);
You can use ParseExact
DateTime.ParseExact(datestring, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
you already know format so you can go for this, but make sure the string is in same format and never changes.
u can try this one:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
DateTime contactsRetriveDat = Convert.ToDateTime(contactsRetriveDate);
if (contactsRetriveDate == "" || toDate.CompareTo(contactsRetriveDat)==0)
{
MessageBox.SHow("");
}

For valid DateTime(Error shows string was not recognized )

I am trying to convert my string formated value to date type with format dd/MM/yyyy. It runs fine but when I enter fromdate(dd/MM/yyyy) in textbox its fine and todate(dd/MM/yyyy) in textbox then it gives an error that string was not recognized as a valid datetime.What is the problem exactly i dont know. same code run on another appliction its run fine but in my application it shows Error.
Below I have used array for required format and split also used.
string fromdate = punchin.ToString();
string[] arrfromdate = fromdate.Split('/');
fromdate = arrfromdate[1].ToString() + "/" + arrfromdate[0].ToString() + "/" + arrfromdate[2].ToString();
DateTime d1 = DateTime.Parse(fromdate.ToString());
try with DateTime.TryParseExact as below
DateTime date;
if (DateTime.TryParseExact(inputText, "MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
if you know the format of input date time you don't need to do any string manipulation.
But you need to give correct Date and Time Format String
I got 5/13/2013 12:21:35 PM in string fromdate
Use DateTime.TryParseExact, You don't have to split your string based on / and then get first three items from the array instead you can simply do:
DateTime dt;
if (DateTime.TryParseExact("5/13/2013 12:21:35 PM",
"M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//date is fine
}
Using single d and single M as it can accomodate single digit as well as double digits day/Month part. You can simply pass punchin as the string parameter, Calling ToString on string types is redundant.
Try :
DateTime.ParseExact(fromdate, "MM/dd/yy", CultureInfo.InvariantCulture)
Obviously you can reformat the above, and use different providers by creating an instance of CultureInfo related to the string you are parsing, and you can modify the format string to reflect that culture or to accommodate more date parts

Datetime conversion in C# - using formats

I need to convert a String to DateTime format, for this I just tried like
DateTime.ParseExact(DateOfBirth,"MM/dd/yyyy",CultureInfo.InvariantCulture);
it's working fine when I pass the value like 05/30/2012.
But if I try to pass the value as 5/30/2012 its showing error:
String was not recognized as a valid DateTime
To fix this I tried like
DateTime.ParseExact(String.Format("{0:MM/dd/yyyy}", DateOfBirth), "MM/dd/yyyy",
CultureInfo.InvariantCulture);
it's still not working. Here If I try String.Format("{0:MM/dd/yyyy}", DateOfBirth) for the value 5/30/2012 its showing the same format instead of 05/30/2012.
How can I fix this, can anyone help me here...
check this link
string to DateTime conversion in C#
Use M/d/yyyy instead of the format specifier you're using. Using only a single M matches months with leading zeros as well. This is also true for d.
assuming your DateOfBirth string is always separated by slashes, you could try something like this:
string[] dateParts = DateOfBirth.Split('/');
DateTime.ParseExact(string.Format("{0:00}", dateParts[0]) + "/" + string.Format("{0:00}", dateParts[1]) + "/" + string.Format("{0:0000}", dateParts[2]));
I think the issue is the format string can't be recognized since DateOfBirth is not a DateTime object. Thus, you enforce formatting by reformatting the string yourself
There is an overload which might be of your interest
DateTime.ParseExact(DateOfBirth,
new[] { "MM/dd/yyyy", "M/dd/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
This should help you take care of single as well as two digit month part (since 5 is failing for you as the format is MM)
Since you have separators in your string (ie /), you can just do;
DateTime.ParseExact(DateOfBirth,"M/d/yyyy",CultureInfo.InvariantCulture);
That will parse either single or double digit days/months. When you use MM/dd/yyyy, you're requiring them both to be double digit numbers, and that's obviously not what you want in this case.
Try just "d" instead of "MM/dd/yyyy".
So, the statement should be:
var date = DateTime.ParseExact(DateOfBirth, "d", CultureInfo.InvariantCulture);
The documentation for this is here:
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
Edit
Oops, I misread the documentation. It should be "M/d/yyyy".
In case you need to make it culture-independent..
var dateTimeFormat = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentUICulture.Name).DateTimeFormat;
dateTimeFormat.ShortDatePattern =
Regex.Replace(Regex.Replace(dateTimeFormat.ShortDatePattern, "[M]+", "MM"), "[d]+", "dd");
var newDate = date.HasValue ? date.Value.DateTime.ToString("d", dateTimeFormat) : null;

Categories