I'm trying to convert a german DateTime value into a french DateTime object.
The value of my item called "_dateFacture" is "08.07.2015 17:23:01"
var stringdate = _dateFacture.ToString(new CultureInfo("fr-FR")); //d2 = "08/07/2015 17:23:01"
var testfinal = DateTime.Parse(stringdate, new CultureInfo("fr-FR")); // testfinal = "08.07.2015 17:23:01"
How is it possible for the object testfinal to get a value like that ?
If you had declared the datatype with each variable, instead of using var, it would have been easier to spot.
string stringdate = _dateFacture.ToString(new CultureInfo("fr-FR"));
DateTime testfinal = DateTime.Parse(stringdate, new CultureInfo("fr-FR"));
testfinal is a DateTime, not a string.
When you look at it in a debugger or view, testfinal is converted to a string using DateTime.ToString() which uses the current culture (which presumably displays dates with a dot).
What you saw is just a representation issue. They are the same DateTime values.
DateTime doesn't have any implicit format. And it doesn't have any IFormatProvider. It just a date and time values. Format is only a subject when you try to get it's textual representation.
I strongly suspect you see this in your debugger or something;
Your stringdate is a string, but your testfinal is a DateTime. If you wanna save your datetime values in your database, don't save their string representations. Put your datetime values directly to your parameterized queries.
Read: Bad habits to kick : choosing the wrong data type
if you want to store testfinal as a datetime, you just need to make sure your var is in fact a DateTime.
DateTime testfinal = DateTime.Parse(stringdate, new CultureInfo("fr-FR"));
To show it you can use a format in the ToString function:
string formattedDate = testfinal.ToString("dd.MM.yyyy HH:mm:ss");
//now your formattedDate will be "08.07.2015 17:23:01"
Related
I want to compare database datetime value that is stored in dd/mm/yyyy format, with the textbox value that is stored in dd-mmm-yyyy format.
I have tired converting the database value to dd-mmm-yyyy format using parseexact-
DateTime dtdb = DateTime.ParseExact(dr["paydate"].ToString(), "dd-MMM-yyyy",null);
and then comparing with the textbox value,
if(dtdb.ToString() != txtpaydate.Text)
But its giving me this error:
String was not recognized as a valid DateTime.
I also tried doing this:
Convert.ToDateTime(dr["paydate"]).ToString("dd-MMM-yyyy")!= txtpaydate.text
but its still giving me the same error. Please let me know how can I solve this issue. Thank you.
you can convert DateTime value and textbox DateTime value to timestamp (from 1970-0-0) then compare it
edited
maybe you want to read rfc3389 about timestamp
You need to parse your textbox into DateTime object and than you can completely free to use general arithmetic operations such as:
if (dtdb > dttb) and etc. If you have any trouble for parsing it, check this page for further information.
If there's any more question, feel free to ask here. But please check stackoverflow before. Have a great day.
string dtdb =dr["paydate"].ToString("dd-MMM-yyyy");
var dt=txtpaydate.Text.ToString("dd-MMM-yyyy");
if(dtdb!= dt)
{
//do what you want
}
As said, it's best to manipulate pure DateTime objects.
You can do it this way:
// Example strings
var myDate1AsString = "31/12/2016";
var myDate2AsString = "31-dec-2016";
// DateTime object used to retrieved the dates as string
var myDate1AsDate = new DateTime();
var myDate2AsDate = new DateTime();
// Parse the strings; if the parse fail, the date is set to DateTime.MinValue
DateTime.TryParseExact(myDate1AsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate1AsDate);
DateTime.TryParseExact(myDate2AsString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate2AsDate);
// Correctly compare the dates
var result = DateTime.Compare(myDate1AsDate, myDate2AsDate);
// or, directly compare a date with the other.
if (!myDate1AsDate.Equals(myDate2AsDate))
{
// Do some stuff.
}
Always use a CultureInfo when parsing date.
I'm revising some legacy code and there is this...
DateTime dateTime = DateTime.Now;
DateTime from = DateTime.Parse(dateTime.ToString("dd/MM/yyyy 00:00:00"));
DateTime to = DateTime.Parse(dateTime.AddDays(8).ToString("dd/MM/yyyy 23:59:59"));
The from and to variables are then used in Linq / Lambda comparisons, so must be a DateTime.
I can't seem to find a way to format a DateTime variable without converting it to a string, and then back to a DateTime, this seems daft to say the least.
Surely there must be a way to format a DateTime without converting it to a string and then back to a DateTime?
There is no need to convert your DateTime to string and then parse it back to DateTime, instead use DateTime.Date like:
DateTime from = dateTime.Date;
DateTime to = dateTime.Date.AddDays(9).AddTicks(-1); //or .AddSeconds(-1) if you want
// accuracy to a second.
A DateTime doesn't have any implicit format. String representations of it have. And Today property sets time part to midnight.
DateTime from = DateTime.Today;
DateTime to = DateTime.Today.AddDays(9).AddSeconds(-1);
How can I convert the String 20120313 to a DateTime object that holds the value 13-Mar-2012?
I fetch it as
DataEffectiveDate = Convert.ToDateTime(reader["date_id"]);
But it fails here already (converting to 1/1/2001)
You need to use DateTime.ParseExact:
DateTime date = DateTime.ParseExact(text, "yyyyMMdd",
CultureInfo.InvariantCulture);
Then if you want it as "13-Mar-2012", you need:
string reformatted = date.ToString("dd-MMM-yyyy");
... optionally passing in whatever culture you want to use for the month names etc.
(Another alternative is to use my Noda Time, which allows you to parse this as just a local date, without any concerns about what time it will use, time zones etc.)
When you have a particular format in mind, ParseExact is helpful:
string s = "20120313";
var when = DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture);
There's also an overload that accepts multiple candidate formats.
Try DateTime.ParseExact:
string date = DateTime.ParseExact(reader["date_id"], "yyyyMMdd", new CultureInfo("en"));
I have a asp Text box as
where the user will fill only a year value, For this value I have Datetime type Property in c# application and Date type column in DB. So I want to convert that txtYear.Text to DateTime But it will only hold and/or show the year. Please help me in this situation.
A DateTime object will always hold a complete DateTime value, you can't use it to store a year only. (what use would that be anyway?) Besides, the datatype of a "year" is int, not DateTime.
So, I'd like to suggest changing your property to datatype int, both in your code and database.
To display just the year use the format "yyyy".
string s = "2011";
DateTime d = new DateTime(int.Parse(s), 1, 1);
Console.WriteLine(d.ToString("yyyy"));
Console.WriteLine(d);
You have to specify the format of the DateTime value you are manipulating:
String dateTimeFormat = "yyyy";
To show only a part of the DateTime value use the following:
dateTimeValue.ToString(dateTimeFormat);
To read a String value that represents a year into a DateTime use the following:
DateTime.ParseExact(stringValue, dateTimeFormat, CultureInfo.InvariantCulture);
DateTime.ParseExact Method (String, String, IFormatProvider) converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime.ToString Method converts the value of the current DateTime object to its equivalent string representation.
Rather than applying any string manipulating function make use of Year property. Check the documentation on the msdn by visiting below link.
DateTime.Year Property
A DateTime always has a full date component. When you create the DateTime instance, you'll need to assign a month and day, but you can ignore them in your usage.
DateTime d = new DateTime(int.Parse(txtYear.Text, 1, 1);
txtYear.Text = d.ToString("yyyy");
Even better would be not to use a DateTime but just use int. If you have only a year, you only need an int.
i assume the text box name is txYear
DateTime dt = new DateTime (Convert.ToInt32(txYear.text),1,1)
save this dt value in database
If you want only the year, why don't you make it of type smallint?
Anyway if you do really want to make it an year,
DateTime x = new DateTime(Convert.ToInt32(txtYear.text), 1, 1);
But make sure you validate that txtYear.text actually does have a valid year.
That is how I did and it worked.
string format = "yyyy";
var CurrentYear = DateTime.Now.ToString(format);
Im working with VS2008, .NET and C#, and I need to send to one of our clients a DATETIME variable.
The problem is that they want the Date in the format Sortable date/time pattern ("s").
When I get the actual datetime, it is a Datetime object. When I format it to the given format is now a String object, and it has the format I want. But after that I can't create a Datetime object from that formatted String with the same format, because it always returns it to the original Datetime format.
More specific:
DateTime currTime = System.DateTime.Now; //(the format is "13/08/2010 09:33:57 a.m.")
String date = String.Format("{0:s}", currTime);// (wanted format "2010-08-13T09:33:57")
DateTime newDate = DateTime.Parse(date);// (original format again "13/08/2010 09:33:57 a.m.")
IFormatProvider culture = new System.Globalization.CultureInfo("", true); //(Invariant Culture)
String format = "s";
DateTime fecha = DateTime.ParseExact(date, format, culture); // (original format again "13/08/2010 09:33:57 a.m.")
Is there a way of getting a Datetime object with the desired format, or Datetime objects use a given format, and you can't format them to the equivalent string formats?
Thx
A DateTime is just a number. It has no intrinsic "format". It is only rendered into a format when converted to a string. Hence, whenever you need a DateTime as a string, you have to specify what format you want it in.
String date = String.Format("{0:s}", currTime);
This can be shorted a bit to :
String date = currTime.ToString("s");
If I understand the question correctly, I think you are getting confused. A DateTime object itself is not formattable, it is essentialy just a numeric value (number of ticks since DateTime.MinValue or whatever it is).
You can convert a DateTime object into a string representation in whatever format you like, but you aren't changing the actual DateTime object.
Every time you use a DateTime value in a place where it needs to be turned into a string (e.g. in string.Format()), C# will generally call the .ToString() method. The DateTime type declares a .ToString() method that has the format you don’t want.
However, DateTime has additional methods, including .ToString(IFormatProvider provider) and .ToString(string format).
Therefore, you can probably achieve what you want if you replace every use of a DateTime variable in the relevant string-like context to one that calls the appropriate .ToString overload, for example:
Instead of
var message = string.Format("The parcel was sent on {0}.", currTime);
use
var message = string.Format("The parcel was sent on {0}.", currTime.ToString("s"));