Convert different format of DateTime to specific String format - c#

Im Getting System.datetime.now from different Machine .Each system having different datetime format as a mension below
16-Oct-12 7:25:22 PM
16/10/2012 7:10:47 PM [DD/MM/YYYY]
10/16/2012 7:10:51 PM [MM/DD/YYYY]
How To convert Different format of DateTime to specific String format ?
string sDateTime = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");

First result of Google search: Custom datetime format strings from MSDN
You have to use the line of code you provided explicitly on the other machines when returning the datetime:
string sDateTime = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");]
This is however not aware of time zones! If your application spans several time zones, you should take that into count too!
Or, even better, you could return the Unix time (milliseconds from 1970-01-01) as a long, and of course the timezone info too, if that is different across the machines... (Beware, .NET expoch time is from 0001-01-01 though!)
Returning Epoch time
I would recommend against using tryParse: You can not reliably determine if a date is in [DD/MM/YYYY] or [MM/DD/YYYY], only when the month of day is greater than 12... And this would lead to mysterious errors. Believe me, been there, done that (the debugging part)...

try the TryParse methode of the Datetime class
Examples from the link:
string[] dateStrings = {"05/01/2009 14:57:32.8", "2009-05-01 14:57:32.8",
"2009-05-01T14:57:32.8375298-04:00",
"5/01/2008 14:57:32.80 -07:00",
"1 May 2008 2:57:32.8 PM", "16-05-2009 1:00:32 PM",
"Fri, 15 May 2009 20:10:57 GMT" };
DateTime dateValue;
Console.WriteLine("Attempting to parse strings using {0} culture.",
CultureInfo.CurrentCulture.Name);
foreach (string dateString in dateStrings)
{
if (DateTime.TryParse(dateString, out dateValue))
Console.WriteLine(" Converted '{0}' to {1} ({2}).", dateString,
dateValue, dateValue.Kind);
else
Console.WriteLine(" Unable to parse '{0}'.", dateString);
}
Notice that in the example its not working for all given strings dates

The problem of your example is the last two formats 16/10/2012 7:10:47 PM [DD/MM/YYYY] and 10/16/2012 7:10:51 PM [MM/DD/YYYY]. If the value is 10/11/2012 7:20:10 PM how can you know that it is Oct 11, 2012 or Nov 10, 2012?
var input = new string []{ "16-Oct-12 7:25:22 PM",
"16/10/2012 7:10:47 PM",
"10/16/2012 7:10:51 PM"};
foreach (var date in input)
{
var result = DateTime.MinValue;
if (DateTime.TryParse(date, out result))
{
Console.WriteLine("Date value: {0}", result);
}
else
{
Console.WriteLine("Cannot parse value {0}", date);
}
}
As you can see, "16/10/2012 7:10:47 PM" could not be parse.

if (DateTime.TryParse(DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), out result))
sDateTime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
else
{
if (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.Equals("dd-MMM-yy")) sDateTime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
else sDateTime = DateTime.Now.Month +"/" + DateTime.Now.Day+ "/" + DateTime.Now.Year + " " + DateTime.Now.ToString("hh:mm:ss tt");
}

Related

String was not recognized as a valid DateTime. : Error only in Server

A Datetime Parse Error Occur in Server which is not in localhost,may because of difference in timezone on localhost and Server ,
Code :
I am trying 24 hr time format to 12 hr(With AM and PM)
string timesx2 = hr2[0]+":" + hr2[1]; // 19:22
string s2 = DateTime.ParseExact(timesx2, "HHmm", CultureInfo.CurrentCulture)
.ToString("hh:mm tt"); // output in localhost is: 7.22 PM
You should use invariant culture (if you don't need to convert to your timezone of course)
string timesx2 =hr2[0] + ":" + hr2[1]; // 19:22
string s2 = DateTime.ParseExact(timesx2, "HH:mm", CultureInfo.InvariantCulture).ToString("hh:mm tt", CultureInfo.InvariantCulture); // output in localhost is: 7.22 PM
and it'l be ok in Indian culture.
Your parsing string is missing a colon.
Your composed time string is of format HH:mm while you try to parse a string composed of HHmm. That will not work.
Also remove the second h from the output format string if you want single digit hours to happen. Otherwise the output will be 07:22 PM.
string timesx2 = hr2[0]+":" + hr2[1]; // 19:22
string s2 = DateTime.ParseExact(timesx2, "HH:mm", CultureInfo.InvariantCulture)
.ToString("h:mm tt"); // output in localhost is: 7:22 PM
Uppercase "H" indicates a 24-hour time and lowercase "h" indicates
12-hour time and will respect the AM/PM in the candidate string.
DateTime.ParseExact("3/21/2015 8:56:04 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture)
Convert your localtime to UTC time
DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(localDatetime); //Convert sent datetime to UTC.
Get Timezone information from zone name. Get Zone name from here
TimeZoneInfo zoneInfo = TimeZoneInfo.FindSystemTimeZoneById(zoneName);
DateTime finalDatetime = TimeZoneInfo.ConvertTime(utcTime, zoneInfo);

DateTime.Parse False positives with string containing dotted separated numbers

I'm parsing datetimes from a text read from SQL Server using DateTime.Parse.
String like these:
5.4.1
1.1.4
12.1.13
were identified as dates, while they are not.
I can't use DateTime.TryParseExact(), since I have to load data in different formats:
dd/mm/yy
dd/mm/yyyy
dd MMM YYYY
dd-mm-yyyy
dd.mm.yyyy
How can I parse dates according to those formats, while ignoring values like shown above?
If we use the dates you have specified you can reach a result with the code below.
See also https://msdn.microsoft.com/en-us/library/h9b85w22(v=vs.110).aspx since it is very well explained.
string[] formats= {"dd/MM/yy","dd/MM/yyyy","dd MMM YYYY","dd-MM-yyyy","dd.MM.yyyy","dd.M.yy","d.M.y"};
string[] dateStrings = {"5.4.1","1.1.4","12.1.13"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new System.Globalization.CultureInfo("en-US"),
System.Globalization.DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
This code will result in:
Converted '5.4.1' to 1/5/2001 12:04:00 AM.
Converted '1.1.4' to 1/1/2004 12:01:00 AM.
Converted '12.1.13' to 1/12/2013 12:01:00 AM.
Please notice the cultureinfo! This can give different outputs according to it's setting. For example: month and date can be switched!
Ps. You can immediately try this working snippet on http://csharppad.com/.
You can let dates be parsed according to your expected formats. Just pass the (fixed, mm != MM) formats to TryParseExact():
string[] formats = { "dd/MM/yy", "dd/MM/yyyy", "dd MMM YYYY", "dd-MM-yyyy", "dd.MM.yyyy" };
string[] dateStrings = { "5.4.1", "1.1.4", "12.1.13", "23.02.2016" };
foreach (var dateString in dateStrings)
{
DateTime parsedDate;
if (DateTime.TryParseExact(dateString, formats, null, DateTimeStyles.None, out parsedDate))
{
Console.WriteLine("{0} was parsed as a valid DateTime: {1}", dateString, parsedDate);
}
else
{
Console.WriteLine("{0} was not parsed as a valid DateTime.", dateString);
}
}

DateTime parse with custom format

I am trying to parse a datetime value using this:
DateTime insertedDateTime = DateTime.ParseExact(tokens[0] + " " + tokens[1], "yyyy-MM-dd mm:hh:ss", CultureInfo.InvariantCulture);
//tokens[0] = 2013-09-05
//tokens[1] = 07:23:32
I am getting this error:
String was not recognized as a valid DateTime.
Any help would be appreciated.
you should write:
DateTime insertedDateTime = DateTime.ParseExact(tokens[0] + " " + tokens[1], "yyyy-MM-dd mm:HH:ss", CultureInfo.InvariantCulture);
because hh means 12h time and HH means 24h time and putting 23 as hour in 12h time is invalid :)
Of course if you are sure that hours are second in your time and you don't want to write HH:mm:ss or hh:mm:ss (for 12h format)
DEMO here
Hours should go first: "yyyy-MM-dd hh:mm:ss"
NOTE: Consider to use 24-hour HH format instead of 12-hour hh format.
You should change your mm:hh:ss to hh:mm:ss because you giving string hour part first.
DateTime insertedDateTime = DateTime.ParseExact(2013-09-05 07:23:32, "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(insertedDateTime);
Output will be;
9/5/2013 7:23:32 AM
Here a DEMO.
For more informations;
Custom Date and Time Format Strings
try to use
string strdate= "yourdate";
DateTime.ParseExact(strdate, "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);

String to dateTime in C#?

How Can I convert following date string to dateTime:
Fri, 18 Dec 2009 9:38 am PST
I tried DateTime.Parse(string)
I got following error:
The string was not recognized as a valid DateTime. There is an unknown word starting at index 25. System.SystemException {System.FormatException}
UPDATE
I tried to get weather from yahoo and I tried to get date like this:
Date = DateTime.Parse(feed.Element(yWeatherNS + "condition").Attribute("date").Value),
I debugged it. date attribute is correct (like above).
Thanks.
I don't think there's anything in the BCL which will parse time zone abbreviations. (They should be avoided where possible anyway, as they can be ambiguous.)
If you don't mind losing the time zone information, you can use something like this:
using System;
using System.Globalization;
static class Test
{
static void Main()
{
string text = "Fri, 18 Dec 2009 9:38 am PST";
DateTime parsed = TrimZoneAndParse(text);
Console.WriteLine(parsed);
}
static DateTime TrimZoneAndParse(string text)
{
int lastSpace = text.LastIndexOf(' ');
if (lastSpace != -1)
{
text = text.Substring(0, lastSpace);
}
return DateTime.ParseExact(text,
"ddd, dd MMM yyyy h:mm tt",
CultureInfo.InvariantCulture);
}
}
Note that that assumes a fixed date/time format and culture. Your needs may vary, and you should also consider using TryParse or TryParseExact if this is user input.
If DateTime.Parse can't figure it out automatically, you can use DateTime.ParseExact where you specify the format being used.
In your case this would be something like, you'll need to replace the 'PST' yourself however:
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "Fri, 18 Dec 2009 9:38 am PST";
dateString = dateString.Replace("PST", "-08:00");
string format = "ddd, dd MMM yyyy h:mm tt zzz";
DateTime result = DateTime.ParseExact(dateString, format, provider);
If your program needs to work with different timezone abbrevations, you'll have to build a Dictionary with abbrevation to time zone offset conversions.

C# How to convert irregular date and time String into DateTime?

I have a program which converts a irregular date and time string into a system DateTime.
However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.
There are only 2 types of date time strings that the program needs to convert:
Thu Dec 9 05:12:42 2010
Mon Dec 13 06:45:58 2010
Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.
May someone please advise on the codes? Thanks!
The codes:
String rb = re.Replace(" ", " 0");
DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
I would really avoid regex and use what's already built-in .NET (TryParseExact method and date formats):
DateTime result;
string dateToParse = "Thu Dec 9 05:12:42 2010";
string format = "ddd MMM d HH:mm:ss yyyy";
if (DateTime.TryParseExact(
dateToParse,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces,
out result)
)
{
// The date was successfully parsed => use the result here
}
You should capture the parts of your datetime into capture groups in the Match Object, then reconstitute them any way you want.
You can use this Regex statement with named groups to make it easier
((?<day>)\w{3})\s+((?<month>)\w{3})\s+((?<date>)\d)\s((?<time>)[0-9:]+)\s+((?<year>)\d{4})
This is sample code which you can try:
var str = "Thu Dec 9 06:45:58 2010";
if (str.IndexOf(" ") > -1)
{
str = str.Replace(" ", " ");
DateTime time = DateTime.ParseExact(str, "ddd MMM d hh:mm:ss yyyy", null);
}
else
{
DateTime time = DateTime.ParseExact(str, "ddd MMM dd hh:mm:ss yyyy", null);
}

Categories