Timespan return wrong value - c#

I have an application that has multiple languages. I'm having a problem that I convert the date from the USA standard to the one we use in Brazil, I'm using this.
DateTime dataCredito = DateTime.Parse(txtDtCredito.Text);
if (Culture == "English (United States)")
{
string dataConvertida = dataCredito.ToString("dd/MM/yyyy");
dataCredito = Convert.ToDateTime(dataConvertida);
}
But after I calculate a time span
TimeSpan ts = dataNota - dataCredito;
The dataNota is 09/10/2016
and dataCredito is 05/10/2016
It's a 4 day difference, but the timespan is calculating the method as the month is 05 and 09, the diferrence is about 123 days, using the USA standard.
How can I change this to get the time span correctly (4 days for this case)?

The problem is the way you convert text to a DateTime object. by not notifying the method, how you want it converted - you implicitly allowed the conversion to be done based on your own locale, when you should have explicitly stated the format this way:
DateTime dataCredito = DateTime.ParseExact("09/10/2016","dd/MM/yyyy",CultureInfo.InvariantCulture);
obviously you should replace "09/10/2016" with your text input, if you need support for single digits use "d/M/yyyy" formatting instead.

In order to parse a DateTime correctly, you need to use the DateTime.Parse(String, IFormatProvider) overload of DateTime.Parse().
The same applies when you are trying to parse any other data type with culture-specific representation.

I Managed to fix this.
I Just add this before the timespan,now the timespan is return the correct 4.
if (Culture == "English (United States)")
{
string dataAmericana = dataCredito.ToString("dd/MM/yyyy");
dataCredito = Convert.ToDateTime(dataAmericana);
string dataNotaNova = dataNota.ToString("dd/MM/yyyy");
dataNota = Convert.ToDateTime(dataNotaNova);
}
TimeSpan ts = dataNota - dataCredito;

Related

US vs Non US DateTime format

My program has to be able to compare not only us style vs us style format but also us style (mm/dd/yyyy) vs non us style (dd/mm/yyyy). How to do it? So far this is what I have and it only works to compare same style:
DateTime my_dt = new DateTime(); // this can be mm/dd or dd/mm
// depending on where it run
DateTime new_dt = Convert.ToDateTime(us_dt);
int compare = DateTime.Compare(new_dt, my_dt);
when my_dt is dd/mm, I got error :
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at update.Program.Process(String ftp_path, String action)
Comparing the DateTime objects isn't the the real problem, it's the parsing. Given you have 2 strict formats here i.e. dd/mm/yyyy or mm/dd/yyyy the following should work
DateTime my_dt = null;
// parse in either US/Non-US format (culture-independant)
DateTime.ParseExact(someDateStr, new[] { "dd/MM/yyyy", "MM/dd/yyyy" }, CultureInfo.InvariantCulture, DateTimeStyles.None out my_dt);
// parse in US format (culture-dependant)
DateTime dt = DateTime.Parse(result3, new CultureInfo("en-US"));
// compare the results
int compare = DateTime.Compare(my_dt, result3);
Format is a property of datetime string representation, i.e. dt.ToString("mm/dd/yyyy").
System.DateTime is format agnostic, independent and unaware. So you can compare any two isntances of it.
Your question doesn't really illustrate what I think is your actual problem. I am guessing you have two date strings in different cultural formats and you want to compare them.
First of all, you need to know the culture or the format of the strings or else you could have unpredictable results.
Cultures can be identified by an LCID. You can find a list here.
So let's say you have a English (US) date string and a English (Canada) string, you could compare them like so:
string americanDateString = "12/31/2013";
string canadianDateString = "31/12/2013";
DateTime americanDate = DateTime.Parse(americanDateString, System.Globalization.CultureInfo.GetCultureInfo(1033); // 1033 = English - United States culture code
DateTime canadianDate = DateTime.Parse(canadianDateString, System.Globalization.CultureInfo.GetCultureInfo(4105); // 4105= English - Canada culture code
int compare = DateTime.Compare(americanDate, canadianDate);
EDIT: You can also use locale short strings (eg. "en-US" or "en-CA") to lookup the CultureInfo as per abatishchev's answer.

How I can get the difference by time string and Datetime now?

i want to calculate a checktime to the time now and get the hours.
I have a string "time" for example...
Jun 06 2013 07:23:06
and with DateTime.Now I get the Time now. The Problem is now that i can't calculate the difference :(
I need them in my Project where I get from the License Server the time from a user and I want to show the difference to now. I want show this in hours.
You can use the Parse method of the DateTIme class to parse a string as a date and the subtract that from now.
TimeSpan diff = DateTime.Now - DateTime.Parse(dateString);
var hours = diff.Hours
The above exsmple of course requires the date to be in a specific format. You can if needed use DateTIme.ParseExact and specify a specific format yourself
You need to first convert your string to DateTime. here you have custom format so you can use DateTime.ParseExact or DateTime.TryParseExact method as below
DateTime dt;
if (DateTime.TryParseExact("Jun 06 2013 07:23:06", "MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// get difference
var inDays = (DateTime.Now - dt).Days;
}
You can use TimeSpan.Hours property like;
Gets the hours component of the time interval represented by the
current TimeSpan structure.
string dateString = "Jun 06 2013 07:23:06";
var differenceHours = (DateTime.Now - DateTime.Parse(dateString)).Hours;
Console.WriteLine(differenceHours);
Here a DEMO.
If you want to convert your custom formatted string to DateTime, you can use DateTime.ParseExact which need exact format matching between string and datetime.
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.
u may try it
DataTime diff = DateTime.Now - Convert.ToDataTime(dateString);
var hours = diff.Hours

How to convert HH:MM:SS string to datetime?

i am having an input string of HH:MM:SS for example 15:43:13,
now i want to convert it to datetime but keep just the hour/time without the date etc
is it possible?
for example
string userInput = 15:43:13;
DateTime userInputTime = Convert.ToDateTime(userInput);
will give me the full date including the year etc,
is there any way to convert it to just HH:MM:SS without triming/substring?
thanks
As others have said, it's a TimeSpan.
You can get a datetime by doing this
string userInput = "15:43:13";
var time = TimeSpan.Parse(userInput);
var dateTime = DateTime.Today.Add(time);
To just get a time span, you can use:
TimeSpan.Parse("15:43:13")
But you should ask yourself why you want to do this as there are some fairly significant gotchas. For example, which 2:33 AM do you want when it's Sunday, November 3, 2013, and daylight savings time is ending? There are two of them.
If you don't need the extra data (year etc.) use TimeSpan
You can convert from the user input to a TimeSpan using Timespan.Parse
for example:
TimeSpan ts = TimeSpan.Parse("6:12"); //06:12:00
Read more here:
http://msdn.microsoft.com/en-us/library/se73z7b9.aspx

date difference between two dates

I want to calculate the date difference between form date and two date..Am using timespan to calculate the difference between two date if date difference is positive means it enter another process falls means it return error message.
My partial code is here..
TimeSpan span = Convert.ToDateTime(txtenddate.Text).Subtract(Convert.ToDateTime(txtstartdate.Text));
int formatted = span.Days;
if (formatted < 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('Invalid date difference ');</script>", false);
}
In the above code input is end date : 30-01-2004 start date : 01-02-2002
but it returns error message : String was not recognized as a valid DateTime.
please give me a solution to solve this with out changing date format...
You should be using ParseExact to get the relevant DateTime.
TimeSpan ts = DateTime.ParseExact("30-01-2004", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture)
- DateTime.ParseExact("01-02-2002", "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
While using Convert.ToDateTime it invokes DateTime.Parse which will try the conversion corresponding to the your current culture setting which as in this case doesn't support the format of DateTime you have, so you should rely on the ParseExact whereby you know the format in which the string is expected and achieve in fetching your result.
You need to specify the culture for the conversion. By default, it should be using the default date format for your PC but this doesn't always work.
You should take a look at this about specifying a format provider for the Convert.ToDateTime method http://msdn.microsoft.com/en-us/library/9xk1h71t.aspx
and this about the DateTimeFormatInfo object you will need to create to handle the culture: http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
You must use CultureInfo maybe the default CultureInfo different from "en-GB";
var cult = new System.Globalization.CultureInfo("en-GB");
TimeSpan span = Convert.ToDateTime("30-01-2004", cult).Subtract(Convert.ToDateTime("01-02-2002", cult));
Your dateformat should be like this. StartDate=1/2/2002 and EndDate=3/1/2004
for days difference
public long getDaysBetweenDates(Date d1, Date d2){
return TimeUnit.MILLISECONDS.toDays(d1.getTime() - d2.getTime());
}
Date difference between days with time
Date startDate = // Set start date
Date endDate = // Set end date
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);

.NET Date Add Days

I have date in this format "1999-05-31T13:20:00.000-05:00" I want to add some hours or days to it . Can some one suggest how to do that with this format and AddDays or AddHours ? Result need to return same format.
Try using DateTimeOffset.Parse. Then use AddDays or AddHours.
It is important to use DateTimeOffset instead of DateTime if you want to preserve the same timezone offset that you parsed.
var dateTimeOffset = DateTimeOffset.Parse("1999-05-31T13:20:00.000-05:00");
var newDateTimeOffset = dateTimeOffset.AddHours(1);
var newDateTimeString = newDateTimeOffset.ToString("O");
if you don't like the way "O" formats, you can use this:
var newDateTimeString = newDateTimeOffset.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK")
This will 100% match to your format.
Example:
txt_del.Text = Calendar1.SelectedDate.ToString("MM/dd/yyyy");
/* for date picking textbox*/
double d2 = double.Parse(txt_till.Text);
/*second textbox for number of days to add*/
DateTime tom = Calendar1.SelectedDate.AddDays(d2);
/*for adding number of days to selected date*/
txt_total.Text = tom.ToString("MM/dd/yy")
Use DateTime.Parse(...) to create a DateTime object. Then you can add days and/or hours, and then ToString() to get the new string.
That looks like datetimeoffset. Perhaps from sql server? You should be able to use the datetimeoffset structure and the parse method. Once you have a datetimeoffset type you can use addhours or related methods.

Categories

Resources