how to get desired datetime format - c#

i want to generate current date and time in a format like this Mon, 10/08/12 12:29:39 . But when i used a code shown below
DateTime date = DateTime.Now;
i am getting like 10/8/2012 12:29:39 PM , but i actually want a format like Mon, 10/08/12 12:29:39 , what change in this code i can use to get the desired output.
I did this code also ,but didnt success
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format));

Console.WriteLine(time.ToString("ddd, MM/dd/yy hh:mm:ss"));

string format = "ddd, MM/dd/yy HH:mm:ss";

Don't forget to provide the Culture (or the InvariantCulture) as a formatting parameter. Otherwise it will default to the UI culture which might not always provide the format that you expect.
string format = time.ToString("ddd, MM/dd/yy hh:mm:ss", CultureInfo.InvariantCulture);

you should read this page for the future
Custom Date and Time Format Strings:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

you can use this code for all detail datetime
string inp;
DateTime inpdate = DateTime.ParseExact(inp, "dd/mm/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
and u too use this code for with out time
ret = pc.ToDateTime(Convert.ToInt32(inp.Split('/')[2]), Convert.ToInt32(inp.Split('/')[1]), Convert.ToInt32(inp.Split('/')[0]), 0, 0, 0, 0);

You can specify the format either by using one of the built in Methods for example:
.ToShortDateTimeString();
or specifying a string format in the parameter of the .ToString() method.
Example:
.ToString("hh/MM/yyyy");
you can find all the available string formats on the MSDN page, or if you simply google it.

Related

Not getting proper date time format in c#

I'm unable get local time . im getting data like this from the api
sample data
2017-03-06T09:34:20.545Z
Desired Out put
3/6/2017, 3:04:20 PM
im getting value like this - 06/03/2017 04:34:20 AM
how to get the proper time in the format "3/6/2017, 3:04:20 PM".
i tried to localize the time but its giving incorrect date time.
data type
public string UpdatedTime { get; set; }
string updtime = bin.timestamp;//03/06/2017 12:51:33
binModel.UpdatedTime = Convert.ToDateTime(updtime).ToString("M/d/yyyy, h:mm:ss tt", CultureInfo.InvariantCulture);//expected time - 3/6/2017, 6:21:33 PM
You have incorrect format here:
"dd/MM/yyyy HH:mm:ss tt"
HH is used for 24 hours format, but you use AM/PM so you need 12 hours format. Use hh.
You sample data is:
2017-03-06T09:34:20.545Z
it means. year is 2017, month is 03, day is 06 and the same for time.
For desired output you need Month/Day/Year. But you use this format:
"dd/MM/yyyy HH:mm:ss tt"
here you get Day/Month/Year.
You should change your format to (also without zeros in front and with comma):
"M/d/yyyy, h:mm:ss tt"
Try this Code:
private void button1_Click(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString("dd/MM/yyyy,hh:mm:ss tt"); // case sensitive
}
I personally always reference this page when I forget how to format timestamps. If you must use strings, and not DateTime, you can do this.
obj.UpdatedTime = string.Format("{0: d/m/yyyy, HH:mm:ss tt", Convert.ToDateTime(data)});
The format of the string can be whatever your choosing, but the page linked has always been the most helpful for me. If you can use a DateTime property, just do this. You will always want to wrap this in a try/catch and verify you're getting a value you want.
obj.UpdatedTime = Convert.ToDateTime(data);
Cheers

converting a string to a DateTime format

I'm trying to parse 09/01/2015 00:00:00 to the format yyyy-MM-ddThh:mm:ssZ using following method:
DateTime.ParseExact("09/01/2015 00:00:00", "yyyy-MM-ddThh:mm:ssZ", (IFormatProvider)CultureInfo.InvariantCulture);
But I'm getting String was not recognized as a valid DateTime
Can anyone tell me why? I believe 09/01/2015 00:00:00 is a valid DateTime format?
From DateTime.ParseExact
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they are not.
I assume your 09 part is day numbers, you can use dd/MM/yyyy HH:mm:ss format instead.
var dt = DateTime.ParseExact("09/01/2015 00:00:00",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Since CultureInfo already implements IFormatProvider, you don't need to explicitly cast it.
I don't understand this. So it means I first have to correct my string
and secondly I can do a ParseExact(). I thought ParseExact could
handle the given string...
ParseExact is not a magical method that can parse any formatted string you suplied. It can handle only if your string and format perfectly matches based on culture settings you used.
Try this code:
var text = "09/01/2015 00:00:00";
var format = "dd/MM/yyyy HH:mm:ss";
var dt = DateTime.ParseExact(text, format, (IFormatProvider)CultureInfo.InvariantCulture);
You'll notice that the format must structurally match the text you're trying to parse exactly - hence the ParseExact name for the method.
The format does not match, you need to change 09/01/2015 into 2015-01-09 or theyyyy-MM-dd part into dd/MM/yyyy.
The ParseExact-method is no ultimate method that converts ANY dateformat into another one, it is simply to parse a given string into a datetime using the provided format. Thus if your inout does not match this format the method will throw that exception.
As a datetime is internally only a number there is no need to convert one format into another at all, so as long as you know your input-format you can build a date from it which has nothing to do with any formatting which you may need when you want to print that date to your output. In this case you WILL need a formatter.
As most people have stated the error is coming from the fact that the date in string format doesn't match the format you are saying it's in. You are saying that 09/01/2015 00:00:00 is in the format "yyyy-MM-ddThh:mm:ssZ", which it's not, hence the error. To rectify this you need to either alter the format the string is in, or more likely, change the format you are saying the date is in. So change "yyyy-MM-ddThh:mm:ssZ" to "dd/MM/yyyy HH:mm:ss".
In a more long term view how are you arriving at that date? Is it possible that the format may change (input but the user)? If so it might be better to try and avoid the error being thrown and handle it better with TryParseExact. To make use of this best I generally output a nullable DateTime and then check if it's null. If you don't do this then if the parse fails it will simply make the output datetime the minimum value.
Something like this should work:
public DateTime? StringToDate (string dateString, string dateFormat)
{
DateTime? dt;
DateTime.TryParseExact(dateString, dateFormat, null, System.Globalization.DateTimeStyles.None, out dt);
return dt;
}
Then you can use it like this:
DateTime? MyDateTime = StringToDate("09/01/2015 00:00:00", "dd/MM/yyyy HH:mm:ss");
if(MyDateTime != null)
{
//do something
}
Another simple way to do this...
var dt = Convert.ToDateTime(Convert.ToDateTime("09/01/2015 00:00:00").ToString("yyyy-MM-ddThh:mm:ssZ"))

C# convert DateTime from one format to another

I thought this would be a really simple, and i've tried to google it and I keep getting the exception String was not recognized as a valid DateTime.
This is my value "2013-10-21T14:10:49" this is what I want to convert it into 10/21/2013 10:49
string sample = "2013-10-21T14:10:49";
DateTime date31 = DateTime.ParseExact(sample, "MM/dd/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);
When you write DateTime.ParseExact(sample, "MM/dd/yyyy HH:mm", ...), you are saying that sample is in the format MM/dd/yyyy HH:mm. Since it is not, it throws an exception.
It's important to know that a DateTime does not have any format associated with it. It's only when you convert it to or from a string that format can come into play. You should probably use something like this:
string sample = "2013-10-21T14:10:49";
DateTime date31 = DateTime.Parse(sample, System.Globalization.CultureInfo.InvariantCulture);
string date31string = date31.ToString("MM/dd/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);
// date31string is "10/21/2013 14:10"
Instead of ParseExact, I used Parse, since the format is recognized by Parse, and I don't see much point in limiting what sort of formats it can accept to only that particular format.
Your string appears to be in format of "Xml-serialized". So it is the job of XmlConvert.
string sample = "2013-10-21T14:10:49";
string converted = XmlConvert.ToDateTime(sample, XmlDateTimeSerializationMode.Unspecified)
.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
You don't need the ParseExact method, the Parse method is sufficient because it allows your date representation. See DateTime - The string to parse for an overview of allowed input formats.
This means the following works:
string sample = "2013-10-21T14:10:49";
DateTime parsed = DateTime.Parse(sample);
Console.WriteLine(parsed.ToString("MM/dd/yyyy HH:mm:ss"));
And the result is:
10/21/2013 14:10:49

C# Datetime format conversion

I have a conversion problem with datetime. I have a date string as MM/dd/yyyy. Now I need to convert it to yyyy-MM-dd.
But I'm facing some error. Please help
public static DateTime ToDBDateTime(string _dateTime)
{
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
string _convertedDate = string.Empty;
if (_dateTime != null || _dateTime != string.Empty)
{
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(_toDBDateFormat);
//_convertedDate = Convert.ToDateTime(_dateTime).ToString(_toDBDateFormat);
/// Debug.Print(sysFormat);
}
return Convert.ToDateTime(_convertedDate);
}
And I want to know that is there is any way to pass the datetime in various formats and it would return the expected format.
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
Please provide some suggestion to solve datetime issues.
I have a date string as MM/dd/yyyy
Right... and yet you're trying to parse it like this:
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
...
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat,
CultureInfo.InvariantCulture)
You need to give a format string which matches your input - so why are you including a time part? You probably just want:
string sysFormat = "MM/dd/yyyy";
However, that's not the end of the problems. You're then converting that DateTime back into a string like this:
.ToString(_toDBDateFormat)
... and parsing it once more:
return Convert.ToDateTime(_convertedDate);
Why on earth would you want to do that? You should avoid string conversions as far as possible. Aside from anything else, what's to say that _toDBDateFormat (a variable name which raises my suspicions to start with) and Convert.ToDateTime (which always uses the current culture for parsing) are going to be compatible?
You should:
Work out how you want to handle being given an empty string or null, and just return an appropriate DateTime then
Otherwise, just parse using the right format.
This part of your question also concerns me:
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
There's no such thing as "the date in format as yyyy-MM-dd". A DateTime is just a date and time value. It has no intrinsic format. You specify how you want to format it when you format it. However, if you're using the value for a database query, you shouldn't be converting it into a string again anyway - you should be using parameterized SQL, and just providing it as a DateTime.
As you have a date in a string with the format "MM/dd/yyyy" and want to convert it to "yyyy-MM-dd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
dt.ToString("yyyy-MM-dd");
Use the inbuilt tostring like this:
Convert.ToDateTime(_convertedDate).ToString("MM/dd/yyyy") or whatever format you want.
I tried this and its working fine.
DateTime date1 = new DateTime(2009, 8, 1);
date1.ToString("yyyy-MM-dd hh:mm:ss tt");
You can apply any format in this ToString.
Hope that helps
Milind

how to convert text to date?

i have this text format:
8/27/2009 8:23:06 AM
Thu Aug 27 12:42:22 2009
08/12/2009 20:22
i need to get this: dd/mm/yyyy
how to do it in C# Winform code ?
thank's in advance
You could parse it with DateTime.Parse(...) and after woods print it with DateTime.ToString().
var date1 = DateTime.Parse("8/27/2009 8:23:06 AM", CultureInfo.GetCultureInfo("en-US"));
var date2 = DateTime.Parse("Thu Aug 27 2009 12:42:22", CultureInfo.GetCultureInfo("en-US")); //Edited the date a little
var date3 = DateTime.Parse("08/12/2009 20:22", CultureInfo.GetCultureInfo("en-US"));
Console.WriteLine(date1.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date2.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date3.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Some of it is maybe redundant for you. I live in DK and have DK culture so I can't parse the same strings as you can if you have a US computer. Therefore I have set the culture explicit. If you have US culture by standard or want to adapt the application for other cultures then you can use:
//for parsing
var date1 = DateTime.Parse("A date");
//for printing
date1.ToShortDateString();
As fletcher, you can use DateTime.TryParse instead if you parse user input or data where you expect flaws in the provided date strings.
For those particular formats I would use the DateTime.TryParse function. I 'm pretty sure only the final string you have provided would be accepted by the parse operation, the TryParse function will return a boolean value indicating the success of the operation. Once you have the resulting DateTime object you can then output a string in ShortDate format using the ToShortDateString function or you can specify a different format if you wish.
DateTime date = new DateTime();
bool parseSucceeded = DateTime.TryParse("08/12/2009 20:22", out date);
if(parseSucceeded)
Console.WriteLine(date.ToShortDateString());
DateTime.Parse("text")

Categories