date difference between two dates - c#

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);

Related

Parse date string with single digit day e.g. 1-11-2017 as well as 12-11-2017

So I have a date String coming in with the short date of today.
For Example "1-11-2017"
//Here i convert the HttpCookie to a String
string DateView = Convert.ToString(CurrDay.Value);
//Here i convert the String to DateTime
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
After running the code I get the error:
FormatExeption was unhandled by user code
An exception of type 'System.FormatException' occurred in
mscorlib.dll but was not handled in user code
Additional information: String was not recognized as a valid DateTime.
1-11-2017 is not in the format of dd-MM-yyyy, specifically the first part. Use d-M-yyyy instead which will use one digit day and month when the value is below 10 (ie. no 0 padding).
Test:
DateTime myDate = DateTime.ParseExact("1-11-2017", "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(myDate.ToString());
If you do not know if there will be 0 padding you can pass an array of acceptable formats, the parser will try each one in order they appear in the array.
DateTime myDate = DateTime.ParseExact("1-11-2017", new string[]{"d-M-yyyy", "dd-MM-yyyy"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Fiddle
The Date format ddstands for The day of the month, from 01 through 31. You either supply it as 01-11-2017 or change your formatter to d-MM-yyyy.
Here's a reference to Custom Date and Time Format Strings
I solved this using yyyy-MM-dd instead of dd-MM-yyyy
(and later converting it to normal dates)
Becouse the var always was the day of today the day can be 1 and 2 digits
CurrDay.Value = DateTime.Now.ToString("yyyy-MM-dd" );
// Convert String to DateTime
dateFrom = DateTime.ParseExact(CurrDay.Value.ToString(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
The comments below helped me find this solution,
Thanks to everyone!
Pass the value like below,
string DateView = Convert.ToString("01-11-2017");
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
It's because ParseExact means you pass the format and the method expects the same date format to be passed as string, that's why you need to pass d-MM-yyyy instead of dd-MM-yyyy.
I you're not sure if the passed string will be with one digit or two then do the following:
string[] digits = DateView.split('-');
DateTime dateTime = new DateTime(digits[2], digits[1], digits[0]);
You even can split using / instead, but you need to make sure the first digit is a day and the second is month, and so on.
My advice is pass ticks instead of string of datetime:
DateTime date = new DateTime(numberOfTicks);
string valueAsStr = date.ToString("dd-mm-yyyy");

change format of datetime.now

I want to get the last seen of user and save it to my sql database in mvc5 . I got the last seen in controller with code like this:
users.userlast=DateTime.Now;
and saved to my database in this format "2015-08-06 12:12:13.443". I want to get datetime only format day,month,year, hour and minute.
I can't use something like this,
var dateTime = DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm", CultureInfo.InvariantCulture);
var text = dateTime.ToString("MMM. dd, yyyy HH:mm");
It did not work because my last seen column is a datetime type not string. What should i do?
Thanks.
Edit:
Like whatsup App., i want to see only hour and minute, not seconds as last seen.
You say that you are storing as a datetime type, in which case the you shouldn't need to convert a string to a DateTime. In fact you shouldn't need to do any parsing.
When you query the database you should get a DateTime, on which you can call the ToString() you want.
to get datetime in format day, month, year, hour and minute only (without seconds, milliseconds), create a new DateTime value before save:
var dt = DateTime.Now;
users.userlast = dt.Date.AddHours(dt.Hour).AddMinutes(dt.Minute);
You don't have to worry about the format you save in the database. When you want to represent it in your specific format you can ToString it accordingly.
I want to get datetime only format day,month,year, hour and minute.
string text = dateTime.ToString("yyyy-MM-dd HH:mm",
CultureInfo.InvariantCulture);
CultureInfo.InvariantCulture is to use your specified culture regardless of the user's current culture.
You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:
DateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Just do like that
var formattedDateTime = yourLastSeenDateTime.ToString("MMM. dd, yyyy HH:mm", CultureInfo.InvariantCulture);
EDIT: Try this as you mentioned in comments
DateTime dbDate = yourLastSeenDateTime;
DateTime newDateTime = new DateTime(dbDate.Year, dbDate.Month, dbDate.Day, dbDate.Hour, dbDate.Minute, 0);

How to Convert string "07:35" (HH:MM) to TimeSpan

I would like to know if there is a way to convert a 24 Hour time formatted string to a TimeSpan.
Right now I have a "old fashion style":
string stringTime = "07:35";
string[] values = stringTime.Split(':');
TimeSpan ts = new TimeSpan(values[0], values[1], 0);
While correct that this will work:
TimeSpan time = TimeSpan.Parse("07:35");
And if you are using it for validation...
TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
// handle validation error
}
Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.
If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:
DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// handle validation error
}
TimeSpan time = dt.TimeOfDay;
As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
Use TimeSpan.Parse to convert the string
http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx
You can convert the time using the following code.
TimeSpan _time = TimeSpan.Parse("07:35");
But if you want to get the current time of the day you can use the following code:
TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;
The result will be:
03:54:35.7763461
With a object cantain the Hours, Minutes, Seconds, Ticks and etc.

How to validate if a "date and time" string only has a time?

I have a single string variable that stores what could be a full date or a partial date:
1) Full Date: 12/12/2010 12:33 AM
2) Partial Date: 12:33 AM (no date field only time)
I'm trying to figure out what would be the best approach to parse the string to figure out if the string is missing the date string or not. The reason is, in my code if the date is missing I will append a default date to the string (such as 1/1/1900). Keep in mind that the time could be in various formats.
Update - My particular answer to this problem.
As all the "posts" have stated, there are multiple answers to this problem, this is ultimately what I used and hope it can help others*:
public DateTime ProcessDateAndTime(string dateString)
{
string dateAndTimeString = dateString;
string[] timeFormats = new string[]
{
"hh:mm tt", "hh:mm:ss tt",
"h:mm tt", "h:mm:ss tt",
"HH:mm:ss", "HH:mm", "H:mm"
};
// check to see if the date string has a time only
DateTime dateTimeTemp;
if (DateTime.TryParseExact(dateString, timeFormats,
CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTimeTemp))
{
// setting date to 01/01/1900
dateAndTimeString = new DateTime(1900, 1, 1).ToShortDateString() + " " + dateString;
}
return DateTime.Parse(dateAndTimeString);
}
*Note: This method is based on the assumption that there are only a specific amount of time formats used in your application, and that it is guaranteed that a properly formatted date and time, or time only string passed in (pre-validation for removal of garbage text).
Use
Convert.ToDateTime(string value, IFormatProviderProvider provider)
Since the string comes in different flavors, provide different format providers as needed.
The order could be:
DateOnly
Time Only
DateTime
The convert will throw an format exception if it fails. If you prefer not to have exceptions, use Datetime.TryParse instead as that returns a boolean.
Depending on how the string is represented you could have more than 3 format providers.
You can try to validate string with a RegEx,
BTW, good regexes for DateTime validation can be found here
Here's one way to do this without knowing all possible time formats:
CultureInfo provider = CultureInfo.CurrentCulture;
DateTime time;
DateTime datetime;
bool isTime = DateTime.TryParse(dateString, provider, DateTimeStyles.NoCurrentDateDefault, out time)
&& time.Date == DateTime.MinValue.Date
&& DateTime.TryParse(dateString, provider, DateTimeStyles.None, out datetime)
&& datetime.Date != DateTime.MinValue.Date);
If the string only has a time then the first TryParse will set the date part to 1/1/0001 or DateTime.MinValue.Date and the second TryParse will set the date part to the current date. This will work unless it is run by Doctor Who after travelling back in time to 1/1/0001.
You can use DateTime.TryParseExact.
This might not be the best but it answers your question:
string dateString = "9:53AM";
if (!dateString.Contains('/')))
{
dateString = DateTime.Now.ToShortDateString() + " " + dateString;
}
Looking at the length of the string will be straight-forward and will support multiple formats. A string with a date and time will most certainly be longer than a string with just a time. However, if your input may have times with high precision (12:30:30:50:20 vs 12/11/11 12:30) and low precision this won't work.
This solution is ideal if you don't need to know the value in the string immediately, and only want to add the default date.
If you support times to the second, for instance, a time will have 8 or less characters and a date-time will have 9 or more.
Given that the time can be in various formats (12/24?) it would be best to user several patterns, in some pre-defined order, trying to parse with each and resolving when the first succeeds.
You can also try
DateTime aTime;
if (DateTime.TryParse(dateString, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.NoCurrentDateDefault, out aTime))
{
//if the there is no date part in the dateString, date will
// default to Gregorian 1/1/0001
}

C# Getting Just Date From Timestamp

If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm
How can I just extract the date from the timestamp?
For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it.
What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time?
DateTime.Parse("2010-05-18 08:36:52:236").ToString("yyyy-MM-dd");
You should use the DateTime type:
DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");
Your format is non-standard, so you'll need to call ParseExact instead of Parse:
DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);
You could use substring:
"2010-05-18 08:36:52:236".Substring(0, 10);
Or use ParseExact:
DateTime.ParseExact("2010-05-18 08:36:52:236",
"yyyy-MM-dd HH:mm:ss:fff",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
date = date.Date; // Get's the date-only component.
// Do something cool.
}
else
{
// Flip out because you didn't get a real date.
}
Get the .Date member on the DateTime
DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
use it like this:
var x = DateTime.Now.Date; //will give you midnight today
x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.
The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part.
Try this:
select convert(datetime,convert(int, #yourdate))
So you convert it to an integer and then back to a data and voila, time part is gone.
Of course subtracting this result from the original value will give you the time part only.

Categories

Resources