How can I turn an ISO date (20140312120000 or 2014-03-12 12:00:00) into "March 12th, 2014 12:00:00"?.
Thanks.
DateTime thisDate1 = new DateTime(2014, 3, 12);
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");
// The example displays the following output:
// Today is March 12, 2011.
You can't parse it with the normal DateTime.Parse method,
DateTime.ParseExact(date, "yyyyMMdd''HHmmss", CultureInfo.InvariantCulture)
I solved it like so: DateTime.Parse(isodate).ToString("MMMM dd, yyyy HH:mm:ss").
What you want to do is to parse the input string as a DateTime and then convert it to the form you want. The ParseExact and ToString methods will do the job.
public string MyFromat(string s)
{
var inputForms = new string[]
{
"yyyyMMdd''HHmmss",
"yyyy-MM-dd' 'HH':'mm':'ss"
};
var time = DateTime.ParseExact(s, inputForms, , CultureInfo.InvariantCulture);
return time.ToString(""MMMM dd, yyyy HH':'mm':'dd", , CultureInfo.InvariantCulture);
}
Your two example forms are not ISO. If you want to parse ISO date times, then use DateTimeOffset for representing the time and use these input forms:
static readonly string[] Iso8061DateTimeForms = new string[]
{
"yyyyMMdd'T'HHmmss",
"yyyyMMdd'T'HHmmss'Z'",
"yyyyMMdd'T'HHmmsszzz",
"yyyyMMdd'T'HHmmss'.'fffffff",
"yyyyMMdd'T'HHmmss'.'fffffff'Z'",
"yyyyMMdd'T'HHmmss'.'fffffffzzz",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'",
"yyyy'-'MM'-'dd'T'HH':'mm':'sszzz",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff'Z'",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz",
};
The full implementation for parsing an ISO 8061 time is:
public static DateTimeOffset ParseIso8061Time(string s)
{
var styles = DateTimeStyles.AllowWhiteSpaces |
(s.EndsWith("Z")
? DateTimeStyles.AssumeUniversal
: DateTimeStyles.AssumeLocal);
return DateTimeOffset.ParseExact(s, Iso8061DateTimeForms,
CultureInfo.InvariantCulture, styles);
}
Related
I have been trying to solve this problem: in the following code, the local variable 'format4' has a month that is a word and I cannot print it with the ParseExact method. I know that I can use the corresponding integer but cannot
figure out how.
using System;
namespace exercise_2
{
class Program
{
static void Main()
{
string format1 = "16/03/2020";
string format2 = "16-03-20";
string format3 = "03/16/2020"; // US format , month before date
string format4 = "March 16, 2020";
DateTime dt_1 = DateTime.ParseExact(format1, "dd/MM/yyyy", null);
Console.WriteLine(dt_1);
DateTime dt_2 = DateTime.ParseExact(format2, "dd-MM-yy", null);
Console.WriteLine(dt_2);
DateTime dt_3 = DateTime.ParseExact(format3, "MM/dd/yyyy", null);
Console.WriteLine(dt_3);
//easier to use the Parse method
//DateTime dt_4 = DateTime.Parse(format4);
//Console.WriteLine(dt_4);
DateTime dt_4 = DateTime.ParseExact(format4, "[MM]" + "[03] dd, yyyy", null);
Console.WriteLine(dt_4);
}
}
}
The format is "MMMM dd, yyyy"
Test code:
Console.WriteLine(DateTime.ParseExact("March 16, 2020", "MMMM dd, yyyy", null));
See also Custom date and time format strings
If the above single line of code does not work then your thread's current culture is not English. To fix this pass the correct culture to the method as the format provider.
Console.WriteLine(DateTime.ParseExact("March 16, 2020", "MMMM dd, yyyy", System.Globalization.CultureInfo.GetCultureInfo("en-US")));
I want to convert a string to a DateTime object. My string will be in this format- "18th Jul 2016" (the date can change). Obviously, .Net does not take this as a valid date format. Is there any easy way to convert this without using any third party library?
I wouldn't use String.Replace since it could be a problem is the current culture's month-name contains the strings you're going to replace.
Instead you could remove this part from the string:
string input = "18th Jul 2016";
string[] token = input.Split(); // split by space, result is a string[] with three tokens
token[0] = new string(token[0].TakeWhile(char.IsDigit).ToArray());
input = String.Join(" ", token);
DateTime dt;
if(DateTime.TryParseExact(input, "dd MMM yyyy", null, DateTimeStyles.None, out dt))
{
Console.WriteLine("Date is: " + dt.ToLongDateString());
}
If you pass null as IFormatProvider to TryParseExact the current culture's datetimeformat is used. If you want to force english names you can pass CultureInfo.InvariantCulture.
Workaround:
string dateStr = "18th Jul 2016";
dateStr = dateStr.Replace("th", "").Replace("st", "").Replace("rd", "").Replace("nd", "");
DateTime date;
if (DateTime.TryParseExact(dateStr, "dd MMM yyyy", CultureInfo.CurrentCulture,
DateTimeStyles.AssumeLocal, out date))
{
}
else
{
// error
}
Its a bit of a fudge but
string result = System.Text.RegularExpressions.Regex.Replace(dt, "[st|th|nd|rd]{2} ", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
DateTime d = DateTime.Parse(result);
I included the space so it doesnt try editing the months.. I did start out with [0-9]{1,2} and replacing it with the number, but that seemed overkill
string dateString = "18th Jul 2016";
dateString = Regex.Replace(dateString, #"^(\d{2})(st|nd|rd|th)", "$1");
var result = DateTime.ParseExact(dateString, "dd MMM yyyy", CultureInfo.InvariantCulture);
Right now I'm using the method stated below and it displays the result in this manner 1/1/0001 12:00:00 AM
string date = "Mon, 15/05/2014";
DateTime alertedDate;
DateTime.TryParseExact(date, new string[] { "ddd, dd/MM/yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out alertedDate);
txtDate.Text = Convert.ToString(alertedDate);
What seems to be the problem here?
Also, my database date value stores the data in MM/dd/YYYY format and my Globalization.CultureInfo is in UK format which is dd/MM/yyyy. Could this cause the error
Change your code to :
string date = "Thu, 15/05/2014";
15/5/2014 is Thursday.
Try
txtDate.Text = alertedDate.ToString("s")
Try this:
string[] formats= { "dd/MM/yyyy" };
string date = "Mon, 15/05/2014";
DateTime dateTime = DateTime.ParseExact(date, formats, new CultureInfo("en-US"), DateTimeStyles.None);
Reference: Example
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);
I have a string strDate that contains selected date.
strDate holds value in the given format- month(3 letters) dd,yyyy
example 1: Feb 22, 2011
example 2: Jul 19, 2011
How can i convert this string value into datetime format of c#?
Have a look at DateTime.Parse. Try using:
DateTime.Parse(yourDateString, CultureInfo.GetCultureInfo("en-US"));
DateTime myDateTime;
if (DateTime.TryParse(myDateString, out myDateTime) == True)
{
// successfully converted to date time
}
If you wrap it in a check of DateTime.TryParse then if there is a case where the string isn't of a correct DateTime format then an exception won't be thrown.
This way you can place an else statement of change to == False and respond to the failed parse. (instead of having to deal with en exception).
var str = "Jul 19, 2011";
DateTime date;
if (DateTime.TryParseExact(str, "MMM dd, yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// the parsing was successful
}
Try this:
DateTime dt = DateTime.ParseExact(strDate, "MMM dd, yyyy", CultureInfo.InvariantCulture);
string myDateTimeString;
myDateTimeString = "19 Feb,2008";
DateTime dt;dt = Convert.ToDateTime(myDateTimeString);
Response.Write(dt.Day + "/" + dt.Month + "/" + dt.Year);
Check this http://msdn.microsoft.com/en-us/library/az4se3k1.aspx