calculation on textboxes that have date value? - c#

I have three textboxes named borrower_date_txt,period_txt and ret_date_txt.
Now, I want to make calculation on those textboxes. I want to enter the date into the borrower_date_txt (not only today's date), and in the period_txt I enter a period for example 5. In the ret_date_txt I want to display the
borrower_date_txt + 5
i.e give me the date after 5 days of borrower_date_txt date value in the ret_date_txt?

DateTime borrowerDate;
if (DateTime.TryParse(borrower_date_txt.Text, out borrowerDate))
{
int days;
if (int.TryParse(period_txt.Text, out days))
{
var retDate = borrowerDate.AddDays(days);
ret_date_txt.Text = retDate.ToShortDateString();
}
}
The important parts of the above code are as follows:
DateTime.TryParse(...): this will return false if the text isn't a valid date; otherwise it will assign the DateTime value to the borrowerDate. This is a way of safe-guarding your code. Parsing dates can get much more complex quickly, but I'm thinking this will likely due for your situation.
int.TryParse(...): this will return false if the text isn't a valid integer; otherwise it will assign the int value to the days. This is a way of safe-guarding your code.
borrowerDate.AddDays(days): this actually adds the days entered to the date entered.
ret_date_txt.Text = retDate.ToShortDateString(): this displays the result in the ret_date_txt text box, and formats it as a short date (i.e. without the time).

Basically, you can use the DateTime.AddDays method in order to increase a DateTime:
try
{
DateTime date = DateTime.Parse(borrower_date_txt.Text);
int period = Int32.Parse(period_txt.Text);
ret_date_txt.Text = date.AddDays(period).ToShortDateString();
}
catch(Exception ex)
{
//Handle parsing errors maybe
}

First you need to parse your text boxes values to proper date time objects:
DateTime Date1= DateTime.ParseExact(TextBox1.Text, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Then you can perform all the relevant DateTime operations on Date1.

Related

Detect the date format C#

I have some automated C# windows services to upload text to the database. The 'text' is generated by a third party application where we don't have any control.
My issue is that the text contains a column for date.
The default date format is DD/MM/YY. But some times we get MM/YY/DD
Is there any tricky way to identify or convert MM/YY/DD to DD/MM/YY. The data might only contain date for three, four days. So I plan to check if the date is in tolerance with three or four days, it will be accepted. Other wise manually correct it.
For example,
14/08/17 is accepted
08/17/14 is not accepted. Logic should convert this to 14/08/17
Any ideas ?
You could try and parse with the good format, if it goes ok there is no problem, it will return the date. If it goes wrong, you tryparse with the 'secondary format'. If everything goes ok, it will return the date.
Note that if the parsed date it's more than 3 days ahead, it won't count as a valid date and will return null.
if(DateTime.TryParseExact(input, "dd/MM/yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue)
{
int daysBetween = (dateValue-DateTime.Now).Days
if(daysBetween < 4)
{
return dateValue
}
}
if(DateTime.TryParseExact(input, "MM/yy/dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue)
{
int daysBetween = (dateValue-DateTime.Now).Days
if(daysBetween < 4)
{
return dateValue;
}
}
return null
If null gets returned, you'll have an invalid date, if not, that will be the parsed date

c# Is it possible to subtract a day in the datetime format

I have the following simple example:
string dt = DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss");
I can't change the DateTime.Now, but I can change datetime format yyyy-MM-dd hh.mm.ss. Following this example the result must be today's date, but I need to get yesterday's date with the same parameters except day (year, month, hours, minutes and seconds). E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it possible to use some "-" operator or something else inside the datetime format to achieve the result?
If you want yesterday's date, you can do this
string dt = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd hh.mm.ss");
DateTime.AddDays() lets you add number of days, positive for future date, negative for past date.
E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it
possible to use some "-" operator or something else inside the
datetime format to achieve the result?
No, it's not possible inside the DateTime format. you can not change any thing. Because it is only for define format of the Date to display in string format. Any addition or subtraction can only be done before converting it to string format as suggested by "Arghya C".
Can you explain your limitation so we can solve your problem.
If you can only influence the date time pattern, than use the roundtrip format and parse the returning string back to a date time, add the calculation and format it into the desired format:
var dateTimeString = badLibrary.GetDateTime("o");
var dateTime = DateTime.Parse(dateTimeString, null, DateTimeStyles.RoundtripKind);
var newDateTime = dateTime.AddDays(-1);
return newDateTime.ToString("yyyy-MM-dd hh.mm.ss");

store minutes to database

hello i'm new to programming i have the following problem
string tt = drpPickuptime.SelectedItem.Text;
DateTime mora = Convert.ToDateTime(tt);
I have also tried this
string tt = drpPickuptime.SelectedItem.Text;
DateTime mora = DateTime.Parse(tt, new CultureInfo("fr-FR")).Date;
and this 1 also
DateTime mora = DateTime.ParseExact(drpPickuptime.SelectedItem.Text, "mm", CultureInfo.CurrentCulture);
but the error is nor rectified. The problem is that i have a combobox and i have put just minuts there which will be selected by user. I want to store that value in database. But in database the data type of that field is datetime. When i change that to string the problem is solved. But isn't it possible to store that string in database with required conditions. Though it is not a good question but i have done my all effort on it and could;nt get the result. Can anyone help me please
The problem is that you cannot create a valid DateTime with just minutes, there needs to be a date (year, month, day).
If you are just storing minutes in the database then I would recommend an int type. If you really must have a DateTime then you will need to store a date too, perhaps Today's date is an option? in which case you can do this:
int minutes = int.Parse(drpPickuptime.SelectedItem.Text);
DateTime dt = DateTime.Today.AddMinutes(minutes);
I think the best would be to change the datatype to bigint, and store it as a timespan. You can store the Ticks property of the timespan in the database, then when you bring it back you just do TimeSpan.FromTicks(database field). And to store it you can do TimeSpan.FromMinutes(your comobobox value), you will have to parse the combobox value to an integer.
You can't store minutes as a DateTime in the database, as #Jon mentioned. You'd have to store the value as an integer. Then if you want to apply those minutes to some date value, you could do:
DateTime d = DateTime.Now.AddMinutes(tt);
or if you want those minutes in the past you could do:
DateTime d = DateTime.Now.AddMinutes(tt * -1);
You could also store it in the database as a string. Then in your code you can do an int.Parse to convert it from a string to an integer.

Date Comparing in C#

i'm currently working on a little project and i'm stuck with a little problem.
I would like my program to call a method CheckDate on boot.
This method would read in a .txt file to see the last saved date in (yyyy/mm/dd) format.
Then it would compare it with todays date and if it's not the same go on with some instructions.I've read the doc here but can't quite find which method best suites my need.
Question 1: Is there a way to get today's date in (yyyy/mm/dd) format?
Question 2: What's the easiest way to compare Dates in C#?
Thanks in advance.
1. DateTime.Now.ToString("yyyy/MM/dd")
2. DateTime.Parse(input).Date == DateTime.Now.Date
You can get today's date as a string by simply formatting a date.
String today = String.Format("{0: yyyy/MM/dd}", DateTime.Now);
String today = DateTime.Now.ToString("yyyy/MM/dd");
I would advise against using a text file as your means of saving data but if you are going with that system the only thing you would have to do is check to see if the date from the text file matches the date you formatted. Simply comparing formatted strings should do the trick.
if (string a == string b)
You could even put it in one line without having to format stuff separately
if (DateTime.Now.ToString("yyyy/MM/dd").Equals("date pulled from txt file"))
What's the easiest way to compare Dates in C#?
Store them not as text but in a DatteTime.
Compare the variables.
If there is a time in both, compare a.Date == b.Date.
Is there a way to get today's date in (yyyy/mm/dd) format?
Yes. This is wrong, though. PARSE The wrong input and compare the parsed data.
There is a DateTime.Compare method that you could use http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx - this should also let you use the built-in < and > operators.
By the letter of the question:
1:
DateTime.Now.ToString(#"yyyy\/MM\/dd")
2:
if(d1 < d2)...
if(d2 >= d1)...
etc.
However.
DateTime dt;
if(DateTime.TryParseExact(readInString, "yyyy-MM-dd", null, DateTimeStyles.AssumeLocal, out dt))
{
if(dt != DateTime.Now.Date)
{
//Code for case where it's no longer that day goes here.
}
}
else
{
//Code for someone messed up the file and it's not a valid date any more goes here.
}
You're doing this for computer-reading, not human-reading, so use the standard format rather than the conventional format (standard as in ISO, but also every country except North Korea has it as the national standard): yyyy-MM-dd (Edit: I see you're in Canada, CSA Z234.5:1989 is the relevant national standard on date-times for technical purposes; it says to use yyyy-MM-dd).
You should do it the other way around, read the string, parse the date, and do the comparison.
you might want to have a look at the FileInfo-Class ... you can compare the LastWriteTime Member to DateTime.Today
DateTime d1 = DateTime.Now;
DateTime d2 = d1.AddMilliseconds(123456789);
string formattedDate = d1.ToString("yyyy/MM/dd");
TimeSpan ts = d2 - d1;
double dayDiff = ts.TotalDays;
double hourDiff = ts.TotalHours;
double minuteDiff = ts.TotalMinutes;
double secondDiff = ts.TotalSeconds;
double milDiff = ts.TotalMilliseconds;
Console.WriteLine("Formatted Date: {0}\r\nDate Diff:\r\nTotal Days: {1}; Total Hours: {2}; Total Minutes: {3}; Total Seconds: {4}; Total Milliseconds: {5}", formattedDate,dayDiff,hourDiff,minuteDiff,secondDiff,milDiff);
Output:
Formatted Date: 2011/12/15
Date Diff:
Total Days: 1.42889802083333; Total Hours: 34.2935525; Total Minutes: 2057.61315; Total Seconds:
123456.789; Total Milliseconds: 123456789
*Edited my initial post to clarify how the "Total" properties work.
//use a TimeSpan do something like this
strCurDate = string.Format(DateTime.Now.ToString(), "yyyy/mm/dd");
FileInfo fiUpdateFileFile = null;
fiUpdateFileFile = new FileInfo(YourFile Location + Your FileName);
if (((TimeSpan)(DateTime.Now - fiUpdateFileFile.LastWriteTime)).TotalHours < 24)
{
// do your logic here...
}
// you could also get at DateTime.Now.Date() or Day.. depending on what you want to do

convert string to date without time

This line
System.DateTime.Parse("09/12/2009");
convert date (string) to 9/12/2009 12:00:00 AM. How can I get a date in the form 9/12/2009.
after explanations I do:
DateTime dt = System.DateTime.Parse(Request.Form["datepicker"]);
dt.ToString("dd/mm/yyyy");
/* and this code have time, why???*/
Your problem is not with the parsing but with the output. Look at how ToString works for DateTime, or use this example:
using System;
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.Parse("09/12/2009");
Console.WriteLine(dt.ToString("dd/MM/yyyy"));
}
}
Or to get something in your locale:
Console.WriteLine(dt.ToShortDateString());
Update: Your update to the question implies that you do not understand fully my answer yet, so I'll add a little more explanation. There is no Date in .NET - there is only DateTime. If you want to represent a date in .NET, you do so by storing the time midnight at the start of that day. The time must always be stored, even if you don't need it. You cannot remove it. The important point is that when you display this DateTime to a user, you only show them the Date part.
Anything parsed to a DateTime object will contain date+time. If no time is sepcified, the assumed value will be 0000hr.
To get the date-only representation, it's up to how you format it to string.
E.g. theDate.ToString("dd/MM/yyyy")
Refer to the MSDN Date and Time Format Strings.
if you want to convert gridview datetime column to date only column use this code :
raddgvDaybook.Rows.ToList().ForEach(x =>
{
DateTime dt = DateTime.Parse(x.Cells["Vocdate"].Value.ToString());
string str = string.Format("{0:MM/dd/yyyy}", dt);
x.Cells["Vocdate"].Value = str;
});
I tested the code it will work if you bind the datetime as string in dgv.

Categories