How to create a readable date and time from a string? - c#

I'm using an api that returns the date as a string, like so:
2011-06-13T21:15:19Z
As you can imagine this is not the easiest format to understand. My goal is to get it to format like this:
9:15pm - 6/13/2011
Anyone know how to accomplish this? Do I need to use a regular expression or is there a way to convert this to a DateTime?
NOTE: I have tried to use the DateTime.ParseExact method but it didn't work. If this is the solution could you please show me how to convert the example above. Thanks.

string date = "2011-06-13T21:15:19Z";
DateTime dt = DateTime.Parse(date);

I just tried it with TryParse and it worked. Using a try parse is better than parse because you can then handle for the cases the string didn't parse. If your certain the string being passed is static, then I guess it isn't necessary.
string Time = "2011-06-13T21:15:19Z";
DateTime t;
if (DateTime.TryParse(Time, out t))
{
//Works
}

DateTime.Parse seems to work fine for that string:
var dt = DateTime.Parse("2011-06-13T21:15:19Z");
Console.WriteLine(dt.ToString("h:mmtt - M/d/yyyy"));
EDIT
If you want to get it the formatted string to look exactly how it is in your question, just throw a ToLower() on it:
Console.WriteLine(dt.ToString("h:mmtt - M/d/yyyy").ToLower());
Also, all of the date and time string formatting options can be found here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

DateTime.Parse is supposed to work with those ISO 8601 date strings.

Use DateTime.Parse.
void Main()
{
var date = DateTime.Parse("2011-06-13T21:15:19Z");
Console.WriteLine(date);
}

The format string you are looking for is "hh:mmtt \- M/d/yyyy".

Related

Datetime parse not working for specific format

Hello experts i am not able to parse the datetime object from following format
2019-12-04T04:26:29:00
in c#. When I trying to parse this format I'll get
04-12-2019 04:26:29
Without T as DateTime object
You can use the ToString() function in the following way to format your DateTime:
DateTime yourDateTime = ...//your DateTime value
yourDateTime.ToString("dd/MM/yyyy HH:mm:ss")//or any other format
You can parse user input like this:
DateTime enteredDate = DateTime.Parse(enteredString);
If you have a specific format for the string, you should use the other method:
DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);
"d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.
Remove the last 2 zeros and try.
Your code is
2019-12-04T04:26:29:00
The suggested code change is
2019-12-04T04:26:29

How to convert "2003-11-05T16:35:30Z" to "11/5/2013 " in c#?

I am having a problem while converting
2003-11-05T16:35:30Z to "11/5/2013"
I tried below
DateTime.ParseExact("2003-11-05T16:35:30Z", "dd/MM/yyyy", null)
but I am not getting the value I expect.
You want to do this:
DateTimeOffset.Parse("2003-11-05T16:35:30Z").ToString("dd/MM/yyyy")
What you're doing is parsing the data as if it were in the format dd/MM/yyyy - instead, you want to parse it as the universal format it is, and then convert it to a string with your format string.
DateTime.Parse will take a string and return a date time. To get a string back out, you simply use the ToString method.
Try This:
string myDate = DateTime.ParseExact("2003-11-05T16:35:30Z",
"yyyy-MM-ddTHH:mm:ssZ",null).ToString("M/d/yyyy");
When parsing you specify the format that you are parsing from, then you format the DateTime value using the new format:
string reformatted =
DateTime.ParseExact("2003-11-05T16:35:30Z", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", null)
.ToString("dd/MM/yyyy");

Custom DateTime formatting in c#

I have a variable which is printed out using the following string format:
var printThis = String.Format("{0:d}, {0:T}", dateAndTimeVar);
Now I have a problem; I need '{0:T}' to display something like '--.--.--' when I have not set any time to the 'dateAndTimeVar'. This seems not supported using the regular DateTime type (showing '00.00.00' by default if there is no time set).
I can change the 'dateAndTimeVar' variable to anything (including other types), but the string formatting must remain the same.
Is there any solution to this?
You would need to create your own IFormatProvider and pass it into the String.Format method like this
String.Format(new MyFormatProvider(), "{0:d}, {0:T}", dateAndTimeVar);
The FormatProvider would then do a pass-through on all formats except T, where you would have your logic for outputting either the native T format for DateTime or --.--.-- if the Time-part of DateTime is 00:00:00.
Read about IFormatProvider on MSDN here
This a list of date time patterns you can use
DateTime.ToString() Patterns | GeekZilla
Cheers
You could simply check if the DateTime contains a time:
String printThis = dateAndTimeVar.Date == dateAndTimeVar ?
String.Format("{0:d}, --.--.--", dateAndTimeVar) :
String.Format("{0:d}, {0:T}", dateAndTimeVar);
You could simply do this:
var printThis = String.Format("{0:d}, {0:T}", dateAndTimeVar)
.Replace("00:00:00", "--.--.--");

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;

DateTime FormatException error

DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
txtDatumDokum.Text is like "09.09.2011".
but i get FormatException error. Must i parse date?
Try DateTime.ParseExact with the dd.MM.yyyy format string
DateTime.ParseExact(txtDatumDokum.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
It's not good to see, anyway try this:
string s = "09.09.2011";
DateTime dt = Convert.ToDateTime(
s.Replace(".",
new System.Globalization.DateTimeFormatInfo().DateSeparator));
You need to tell us why the text input is using this format. If it is because the user enters it this way, then you need to make sure that the format matches that given by Thread.CurrentCulture.DateTimeFormat.ShortDatePattern. Changing the culture (by setting
Thread.CurrentCulture) to an appropriate value will then solve your problem.
If you are supposed to parse the input no matter what format it is in, then you will need to do some manual processing first (perhaps remove spaces and other delimiter characters from the input with string.Replace) and then try to parse the date using DateTime.ParseExact and a known format string.
But it all depends on why the input has that format, and why your application's current culture does not match it.
You could try this, TryParse avoids parsing exceptions.. Then you just need check result to be sure that it parsed.
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, out datuMDokumenta);
You will have to determine if this is a good solution for your application.
See this example:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
Judging by the date you gave you need to include a culture, de-DE accepts 01.01.11 type of dates but I'm not sure which one you actually want to use, you'll need to decide that.. the Code would look like this:
using System.Globalization;
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, CultureInfo.CreateSpecificCulture("de-DE"), DateTimeStyles.None, out datuMDokumenta);
A list of cultures can be found here, select the appropriate one for you:
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx
The plus here is that this code is a bit more work but it is very difficult to break. Assuming you are using a free text entry on a TextBox you don't want to be throwing exceptions.
Yes you have to parse input date in current culture.
string[] format = new string[] { "dd.MM.yyyy" };
string value = "09.09.2011";
DateTime datetime;
if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out datetime))
//Valid
else
//Invalid
DateTime dt = Convert.ToDateTime(txtDatumDokum.Text)
It is right...there is no isssue
During a Deserialization call under compact framework 3.5 i've had some unexpected behaviour before.
I've converted from using the OpenNETCF serialization classes to the framework XML serialization class. In doing so, the default time format has changed and the order of property/public members. So long story short, i've exposed a text property which converts my date-times back to the format my VB6 application is expecting.
Dim dumbDate As New Date
Dim formats() As String = {"yyyy-MM-ddTHH:mm:ss.fffzzz", _
"yyyy-MM-dd HH:mm:ss:fffffffzzz"}
_datetimeTaken = dumbDate.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
' There is something wrong with compact framework during the Serialization calls.
' calling the shared method Date.Parse or Date.ParseExact does not produce the same
' result as calling a share method on an instance of Date. WTF?!?!?!
' The below will cause a "Format" exception.
'_datetimeTaken = Date.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
Date.blah doesn't work. dumbDate.blah works. strange.
public static void Main(string[] args)
{
var dt = new DateTime(2018, 04, 1);
Console.WriteLine(dt);
string month = dt.ToString("MMMM");
Console.WriteLine(month); //April
month = dt.ToString("MMM");
Console.WriteLine(month); //Apr
month = dt.ToString("MM");
Console.WriteLine(month); //04
Console.ReadKey();
}
your code:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
try changing this to:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum);
and when u print the date/time
print datuMDokumenta.Text

Categories