I have problem in converting system datetime format to specific format.
for eg: DateTime dt=new DateTime();// It will return 11/15/2016 10:23 AM as per my system format.
But I have to convert into this format-- 20161115(yyyyMMdd hh:MM:ss). I can able to achieve this using `DateTime.Now.ToString("yyyyMMdd hh:MM:ss")? .
But its returning String format. I want in DateTime format.
DateTime as an object has no format. It contains the information as an internal numeric valus and is only formatted to string representation by your IDE or code. You don't change the format for it.
Only when you want to output it somewhere you set the format and you get a string for it.
Your DateTime is an object. That means the values are saved into its properties shown below.
If you want the DateTime to display in a different format than the default format then you use the ToString(yourFormat) method to format it. That will not change the data or the position of the properties if thats what you are expecting. (the term position of the properties itself is meaningless)
Its just representation. Just like how you have data in you database as tables but in UI you show it as a fancy HTML.
Internally the object saves data into each property and provides a default representation of it DateTime.Now.ToString(), And only when you dont want the default DateTime format you have the flexibility to format it into your choice.
So if your idea was to use this string date time for any code logic then you will just parse it into DateTime object by giving it the format the string is in like
DateTime date = DateTime.ParseExact(strDate, "yyyyMMdd hh:MM:ss", CultureInfo.InvariantCulture)
Now your string data is parsed into object and you can fetch the values as
date.Date , date.Millisecond etc
Here you go:
string str = DateTime.Now.ToString("yyyyMMdd hh:MM:ss");
DateTime dt = DateTime.ParseExact(str, "yyyyMMdd hh:MM:ss", CultureInfo.InvariantCulture);
DateTime is a class with various properties and methods associated with it. You can't really return a DatTime object in a different "format" - it is just a representation of a point in time. You can however, represent a DateTime object as a stirng foramtted in a specific way. So what you are doing is correct:
DateTime.Now.ToString("yyyyMMdd hh:MM:ss")
Do this when you need to display the DateTime in a readabel format, such as in a log file or on a UI. If you need to pass a DateTime as a parameter, pass the entire object, not just a string representation of it.
DateTime.ParseExact(dateString, "yyyyMMdd hh:MM:ss", null);
Related
So last week, the way our application worked was that the back-end team was storing dates as a string in YYYY-MM-DD formats. This week, they changed it to be a DateTime object instead of a string. So now I'm just creating a DateTime object from the string value on this particular DateTime control we use.
So basically with our custom control , it was like this:
mySearchModelObject.fromDate = myDateRangeControl.Values[0]; //string
mySearchModelObject.toDate = myDateRangeControl.Values[1]; //string
Now it's more like this:
DateTime fromDate, toDate;
DateTime.Tryparse(myDateRangeControl.Values[0], out fromDate);
DateTime.Tryparse(myDateRangeControl.Values[1], out toDate);
mySearchModelObject.fromDate = fromDate;
mySearchModelObject.toDate = toDate;
But searching with the same date range as last week yields different results from the DB.
I'm wondering if it's because our dates were "YYYY-MM-DD" as strings, but now it's getting a date time object in whatever the system's format is + the time itself.
So is there a way to format my DateTime object to still have it in the same YYYY-MM-DD format?
Use DateTime.TryParseExact and provide "yyyy-MM-dd" as format string.
See http://msdn.microsoft.com/en-us/library/h9b85w22
you can do fromDate.ToString("yyyy-MM-dd") to have a date formatted as YYYY-MM-DD
see msdn on standard and custom datetime format
see demo https://dotnetfiddle.net/NZz0HG
also if mySearchModelObject.fromDate is of type object, you can assign a DateTime or a string, no compiler warnings/error.
But when is used, maybe with mySearchModelObject.fromDate.ToString() you get a different result, before was '2014-12-31' and now 12/31/2014 12:00:00 AM
the string is 20131024174621 which is year =2013, month=10, date=24, hours=17, minutes=46, seconds=21
What I am trying to do is to convert and format it into 2013-10-24 17:46:21.
I have tried my luck as the code below however it return such error :
String was not recognized as a valid DateTime.
String timestamp = "20131024174621";
String converted = DateTime.Parse(timestamp).ToString("yyyy-MM-dd HH:mm:ss");
What should be the way of doing it right?
You have to use ParseExact.
void Main()
{
String timestamp = "20131024174621";
var date = DateTime.ParseExact(timestamp, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
Console.WriteLine (date.ToString("yyyy-MM-dd HH:mm:ss"));
}
Output:
2013-10-24 17:46:21
DateTime.ParseExact( timestamp, "yyyyMMddHHmmss", CultureInfo.InvariantCulture ).ToString( "yyyy-MM-dd HH:mm:ss" );
Since other two answer is correct, I want to point the root of your problem.
DateTime.Parse method uses Standard Date and Time Format Strings. From How Standard Format Strings Work
In a formatting operation, a standard format string is simply an alias
for a custom format string. The advantage of using an alias to refer
to a custom format string is that, although the alias remains
invariant, the custom format string itself can vary. This is important
because the string representations of date and time values typically
vary by culture. For example, the "d" standard format string indicates
that a date and time value is to be displayed using a short date
pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For
the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is
"yyyy/MM/dd"
In 20131024174621 string, you need yyyyMMddHHmmss format for your current culture. Looks like your culture doesn't have this format and that's why you get this error.
For this kind of non-standart format string, you can use custom date format.
Any string that is not a standard date and time format string is
interpreted as a custom date and time format string.
As I wrote in third paragraph, this kind of date formats is based on culture. When you have this kind of custom date strings, in most case using DateTime.ParseExact Method (String, String, IFormatProvider) with specific culture is the best choice.
I have a string that has a date stored in it.
String date = "03-05-2013 00:00:00";
I parsed it to Datetime as follows:
DateTime Start = DateTime.Parse(date);
Start.ToString() gave me "3/5/2013 12:0:00 AM"
I also used:
DateTime Start = DateTime.ParseExact(date,"dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture);
Then, Start.ToString() gave me "3/5/2013 12:0:00 AM", which is the exact same result as the previous one. I need to keep the original formatting. How may I do it? Thanks.
The format you parse with does not dictate how the DateTime is formatted when you convert the date back to a string. When you call ToString on a date it pulls the format from the current culture of the thread your code is executing on (which defaults to the culture of the machine your on).
You can override this by passing the format into ToString() i.e.
Start.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
See Custom Date and Time Formats.
You need to pass the format in the ToString() call.
Start.ToString("dd-MM-yyy HH:mm:ss");
I need to keep the original formatting.
Then you need to apply the same pattern again when you call ToString:
string formatted = Start.ToString("dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(Note that you should specify the same culture when formatting as you did when parsing, to avoid things like the time separator from changing.)
Note that for some formats this still might not give the exact original representation - if you're using a format which includes the text for a month, for example, that would match case-insensitively, so input including "MARCH" would be reformatted as "March".
A DateTime value is just a date and time (and a "kind", but that's another story) - it doesn't maintain a textual representation any more than an integer does. It's important to differentiate between the inherent data in a value and a textual representation of that data. Most types which have multiple possible textual representations have no notion of keeping "the original representation" alongside the data.
I have a date and time which should be copied to DateTime object without changing its format.
Is there a way to resolve it?
Pls see the code below
string dateTime = "07/20/11 14:40:28";
DateTime copyDateTime = Convert.ToDateTime(dateTime);
string dateTime2 = copyDateTime.ToString();
Output:
{7/20/2011 2:40:28 PM}
If you notice the output, it got changed to PM. I want it as it is. How to get it?
EDIT:
I want dateTime2 to have the value exactly as it was for dateTime.
Format is not intrinsically associated with the DateTime. Format is simply a display property.
If you need to display it in your preferred format than simply call:
Console.WriteLine(copyDateTime.ToString("G"));
See MSDN for a complete list of standard format strings.
Before outputting, you need to convert the DateTime back into a string. By default, it simply calls "ToString" which uses the default DateTime format configured for the current user/locale.
Use ToString and specify a format to convert the datetime back into a String, then you can control the format.
I have a text box in which a user is supposed to enter a date in MM/dd/yyyy format. This date is stored as yyyy/MM/dd in the database.
I want the user to enter the date in MM/dd/yyyy format and later I want to convert it to yyyy/mm/dd so that I can query the database.
How can I convert the user input date MM/dd/yyyy to yyyy/mm/dd?
If you're certain of the input string's format, use DateTime.ParseExact specifying "MM/dd/yyyy", then return the DateTime using .ToString with the appropriate "yyyy/MM/dd" format string.
There's no need to reference anything in the System.Globalization namespace for this.
That said, your database should be storing dates with a datetime format, rather than a string, in which case the format doesn't matter as your DBMS should do the conversion for you.
You can parse the date and format the result:
string str = Date.Parse(myDate).ToString("yyyy/MM/dd");
Alternatively, if the current culture doesn't support that date format and you've already validated the input:
string items[] = myDate.Split('/');
string str = items[2] + "/" + items[0] + "/" + items[1];
When you said globalization, I assume you want the change to be automatic according to current culture
You can setup culture (at Global.asax.cs I suggest)
System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("the culture you want to set"); //
you do not need to touch any datetime thing, it just happened when you output them.
One thing is not the other.
Not sure why you want to insist on the text entered being MM/dd/yyyy, or why you haven't used a date time picker to make sure it is a date.
But at the point you get the content of the textbox as a date, parse it based on globalisation, or a set of acceptable formats. Now it is a date, and assuming it's a date in the database, format is irrelevant until you come to populate the text box, with some content from the DB, inwhich case you use DateTime's ToString method witha globalisation parameter, usually CultureInfo.CurrentCulture, or if you've got away with it CultureInfo.InvariantCulture.
If it's a string in the DB, then this is the least of your problems.
They key point is if you use dates properly, format is only relevant for Parse, and ToString type methods.
i am using
IFormatProvider culture=new CultureInfo("en-GB",true);
sqlcommand cmd=new sqlcommand("query",con);
cmd.Parameters.AddWithValue("#date",DateTime.Parse(txtdate.Text.Trim(),culture,DateTimeStyles.NoCurrentDateDefault).Date);
for this to work the format property must be set to dd/MM/yyyy
and text box read only property must be false