how to work with double in textbox? - c#

I would like to write a code that reads a time the user wrote into textbox1, lets say 09:00 (hh:mm), save it into a variable, then takes this variable and adds 08:40 to it and Outputs then the outcome 17:40 into textbox2.
The Problem is, when working with double it is working well, but I need to use the hh:mm - Format, I know some languages have the Option to declare a variable as time but it seems like c# isnt doing this. so whats the solution?
thats my current code
void CmdWriteClick(object sender, EventArgs e)
{
string varstr = textbox_1.Text;
double muss = 8.40;
double vardb = Convert.ToDouble(varstr);
double end = vardb + muss;
textbox_2.Text = end.ToString();
}
this would of course Output me double-numbers. so if varstr is 08.30 it would Output 16,7 when I Need to make it Output 17:10. Any help is appreciated
thank you guys

You shouldn't be using a TextBox for this. You have a specific control to take care of dates and times: DateTimePicker.
Add one of these to your form. If you only want the user to modify the time, disallowing date changes, you can do the following:
public myForm()
{
InitializeComponent();
....
myDateTimePicker.Format = DateTimePickerFormat.Custom;
myDateTimePicker.CustomFormat = "HH:mm"; //Shows only hours and minutes in 24h format
myDateTimePicker.Value = DateTime.Now.Date; //sets the time to today at 0:00
myDateTimePicker.MinDate = DateTime.Now.Date;
myDateTimePicker.MaxDate = DateTime.Now.Date.Add(new TimeSpan(23, 59, 59)); //User can't change date.
}
private DateTime newTime;
private void myDateTimePicker_ValueChanged(object sender, EventArgs e)
{
newTime = myDateTimePicker.Value.AddHours(8.5);
}
Obviously if you want the user to set the date too, then simply change the MinValue and MaxValue restrictions to your requirements (if any) and choose one of the predefined format options instead of DateTimePickerFormat.Custom.

Try this :
dateValue.AddHours(8);
dateValue.AddMinutes(30);

You can use DateTime instead of double.
private void button1_Click(object sender, EventArgs e)
{
DateTime dateTime = DateTime.ParseExact(textBox1.Text, "HH:mm", System.Globalization.CultureInfo.CurrentCulture);
TimeSpan time = new TimeSpan(8,40,0);
DateTime outputTime = dateTime.Add(time);
textBox2.Text = outputTime.ToString("HH:mm");
}

You could do something like this:
string input = textbox_1.Text;
DateTime inputTime;
if (DateTime.TryParseExact(input, "HH:mm", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out inputTime))
{
DateTime outputTime=inputTime.AddHours(8).AddMinutes(40);
textbox_2.Text = outputTime.ToString("HH:mm");
}
Basically, you parse the input string to a DateTime variable, add the time you need and then convert back to string to show it in your TextBox

If you really want to do it with double, you have to think about the conversion from minutes to whole numbers. 8.4 would be then 60 * .4 = 24 minutes.
For the rest, the text string you can parse using TimeSpan.Parse and you can write a custom function that would parse the double to a TimeSpan and then simply add the 2 together, like so:
using System;
namespace TimeParser {
class Program {
static TimeSpan GetTimeFromText( string text ) {
if ( string.IsNullOrWhiteSpace( text ) ) {
return TimeSpan.Zero;
}
return TimeSpan.Parse( text );
}
static TimeSpan GetTimeFromDouble( double value ) {
if ( value <= 0 ) {
return TimeSpan.Zero;
}
int hours = (int)Math.Floor( value );
int minutes = (int)(( value - hours )*60);
return new TimeSpan(0, hours, minutes, 0);
}
static TimeSpan GetAddedTime( string input, double time ) {
var textTime = GetTimeFromText( input );
return textTime.Add( GetTimeFromDouble( time ) );
}
static void Main( string[] args ) {
var totalTime = GetAddedTime( "8:30", 8.67 );
Console.WriteLine( totalTime ); // 17.10
}
}
}

Related

How do i assign back the DateTime.Now from a string?

The code:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
DateTime.Now = time;
}
time now for example show the saved datetime.now could be minute ago or an hour ao.
the datetime.now is saved after my program is finished to make an operation.
dt = the current datetime now i use this method in the constructor.
What i want to do is to calculate the time that have been passed between the last saved datetime.now(time) and the current datetime.now(dt).
If the time that have been passed is 20 minutes or more enable true a button.
You cannot set DateTime.Now You need to create an instance of the DateTime object.
Then to get the difference you can say
TimeSpan diff = DateTime.Now - MyDateTime;
This has a property called TotalMinutes that you can use for your check.
if (diff.TotalMinutes >= 20)
{
//Do sommething
}
You can try this code
DateTime date;
if (DateTime.TryParse(time, out date))
{
TimeSpan diff = date - dt;
if (diff.TotalMinutes >= 20)
{
//Do sommething
}
}
Every time you run this method you need to persist the value somewhere. I'm going to call that variable _lastTime. That's going to be a DateTime. Further, you'll need a variable for the actual elapsed time between those two, we'll call that _elapsedTime. That's going to be a TimeSpan. With that in mind, consider this code:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
var dt = DateTime.Parse(time);
_elapsedTime = dt.Subtract(_elapsedTime);
_lastTime = dt;
}
You get an instance of a DateTime from a string using Parse
DateTime dt = DateTime.Parse(time)
and then you get get the time Now using
DateTime.UtcNow; or DateTime.Now;
and subtract one from the other and format as appropriate for you output
You can do this using TimeSpan.
you need to get the Difference in Minutes
DateTime dt1;//get your first date
TimeSpan duration = DateTime.Now - dt1;
if(duration.Minutes>20)
Button1.Enabled=true;
I think your looking for this:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
DateTime lastTime = DateTime.Parse(time);
if (DateTime.Now - lastTime > new TimeSpan(0, 20, 0))
{
//It's passed more than 20mins from last save.
}
}
You can check the time elapsed by using the TimeSpan class.
private void beginOperstionChecker(DateTime dt)
{
if(TimeSpan.FromMinutes(20) == DateTime.Now - dt)
{
//do your stuff here
}
}

Using DateTime With input from a textbox.text

I have this code that when executed gives me 74 Days, which is correct, but the date for oldDate has to come from a TextBox. Does anyone know how to do this as the DateTime only takes three integers.
private void myButton_Click(object sender, RoutedEventArgs e)
{
string myDate = myTextBox.Text;
DateTime oldDate = new DateTime(2013, 6, 5);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = oldDate - newDate;
// Difference in days.
int differenceInDays = ts.Days;
differenceInDays = ts.Days;
myTextBlock.Text = differenceInDays.ToString();
}
You can parse the date from the user:
string myDate = myTextBox.Text;
DateTime oldDate;
if (!DateTime.TryParse(myDate, out oldDate))
{
// User entered invalid date - handle this
}
// oldDate is set now
That being said, depending on the UI framework, a more appropriate control (ie: the DateTimePicker from the extended WPF toolkit, etc) may be easier to use.
From your code you have to obtain oldDate from myTextBox, which you have stored in myDate string variable. You can convert it to datetime
oldDate=Convert.ToDateTime(myDate);
But since it might cause exception use following
`DateTime myyDateTime;if(DateTime.TryParse(myDate, out myDateTime){//use your date difference code here}

How to change "ddd" datetime format to a number view

I want to make that code to show me a current datetime on my pc clock when i click a button... i did it with that code listed down. But here is my question how can i make the "ddd" (day of a week) to be shown in number, not in words, I mean:
00-sunday
01-monday
and etc. ...
This is my code for the button:
private void SetClock_Click(object sender, EventArgs e)
{
SetClock.Click += new EventHandler(SetClock_Click);
{
DateTime time = DateTime.Now;
string format = "yy-MM-dd-ddd-hh-mm-ss";
txtSend.Text = time.ToString(format);
}
}
What i have to add to make it. Thanks
txtSend.Text = string.Format("{0:yy-MM-dd}-{1:00}-{0:hh-mm-ss}", time, (int)time.DayOfWeek);
A format isn't required, you can just cast DayOfWeek to an int:
var dayAsInt = (int)DateTime.Now.DayOfWeek;
Looking at the Custom Date and Time Format Strings page, there doesn't appear to be a format string for it :-(
The following should do it:
txtSend.Text =
time.ToString("yy-MM-dd-") +
((int)time.DayOfWeek).ToString("00") +
time.ToString("-hh-mm-ss");
You could use this to get the day of week numeric
int dayofweek = (int)DateTime.Now.DayOfWeek;

How to delete data from selected Date to current Date using DateTimePicker

My problem is to delete data from given date to current date,
My code works fine for deleting the data by the date given in the DateTimePicker.
i want to delete the data from given date in DateTimePicker to CurrentDate.
For example:
In subfolder123 the data is available from 20100131 to 20110531 (Date Format yyyyMMdd).
I want to delete the date from 20100215 to 20110531.
Hope you understood my Question and problem.
Is there any suggestions?
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
string todaysDate = dateTimePicker1.Text;
int FinalDate4 = 0;
string Destinationnsefx = "C:\\folder\\subfolder\\subfolder123";
int xyz = 0;
string SecSym = (9722).ToString();
MWriterClass writerdelete1 = new MWriterClass();
try
{
writerdelete1.OpenDirectory(Destinationnsefx);
writerdelete1.OpenSecurityBySymbol(SecSym);
FinalDate4 = int.Parse(todaysDate);
if (writerdelete1.get_bDateExists(FinalDate4))
{
try
{
writerdelete1.DeleteIntradaySecRecordEx(FinalDate4, 080000, 240000);
}
catch
{
}
}
writerdelete1.CloseSecurity();
writerdelete1.CloseDirectory();
}
catch
{
}
}
Thanks in advance.
It sounds like you get a date from your DateTime picker and you need to work from that start date to your end date, correct?
In that case, look at the AddDays method for a DateTime object.
For example, this snippet of code will start at 4/1/2011 and print every date from then until today, in the format you specified.
var workingDate = new DateTime(2011, 4, 1);
while (workingDate < DateTime.Today)
{
workingDate = workingDate.AddDays(1);
Console.WriteLine(string.Format("{0:yyyyMMdd}", workingDate));
}

Hour from DateTime? in 24 hours format

So i have this DateTime? and what i want to do is to obtain the hour but show it in 24 hours format.
For example:
If the hour is 2:20:23 p.m. i want to convert it to 14:20 and that's it.
I'm working with Visual C#.
Any ideas please, thank you.
I have something like this
public static string FormatearHoraA24(DateTime? fechaHora)
{
if (!fechaHora.HasValue)
return "";
string retornar = "";
//here goes what i need
}
You can get the desired result with the code below. Two 'H' in HH is for 24-hour format.
return fechaHora.Value.ToString("HH:mm");
date.ToString("HH:mm:ss"); // for 24hr format
date.ToString("hh:mm:ss"); // for 12hr format, it shows AM/PM
Refer this link for other Formatters in DateTime.
Using ToString("HH:mm") certainly gives you what you want as a string.
If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:
TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;
Try this:
//String.Format("{0:HH:mm}", dt); // where dt is a DateTime variable
public static string FormatearHoraA24(DateTime? fechaHora)
{
if (!fechaHora.HasValue)
return "";
return retornar = String.Format("{0:HH:mm}", (DateTime)fechaHora);
}
Try this, if your input is string
For example
string input= "13:01";
string[] arry = input.Split(':');
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)
{
DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)),
int.Parse(timeinput.Substring(2, 2)), 0);
return startTime.ToString("hh:mm tt");
}
out put: 01:01
Another method
var time = DateTime.Now;
string foo = $"{time:HH:mm}";
Where I find this useful is if there is more than just the time in the string.
string bar = $"The time is {time:HH:mm}";

Categories