I am making a NetcafeProgram in C# and I want to get the current DateTime. I want my output like this (hr.mins)"0.25". I have the current DateTime but I want to show it like this (hr.mins)"0.25" in the labelTime_1 but it is not working. This is the command which I used
starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
and I changed it to
starttime_1 = DateTime.Now.ToString("h.mm");
and then I wanted to get the duration like this
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
but it gives me errors.
Here is a Screenshot of My Formv:
I want the time to get posted On that Time Elapsed Label but it doesn't work. Here is the coding of BtnStop1
private void btnStop_1_Click(object sender, EventArgs e)
{
//string duration = Convert.ToInt32(((starttime_1) - (endtime_1)));
gbx_1.BackColor = Color.LimeGreen;
btnStop_1.Enabled = false;
//endtime_1 = DateTime.Now.ToString("h:mm:ss tt");
//TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
endtime_1 = DateTime.Now.ToString("h.mm tt");
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
lblTime_1.Text = Convert.ToString(duration);
string var = "Cabin One is Free";
btnStart_1.Enabled = true;
HP_1.Enabled = true;
CR_1.Enabled = true;
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
}
Coding of BtnStart
private void btnStart_1_Click(object sender, EventArgs e)
{
gbx_1.BackColor = Color.Red;
btnStart_1.Enabled = false;
//starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
starttime_1 = DateTime.Now.ToString("h.mm tt");
lblTime_1.Text = "CountingTime";
string var = "Cabin One is Occupied";
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
HP_1.Enabled = false;
CR_1.Enabled = false;
}
Here Are My Variables
public string starttime_1;
public string starttime_2;
public string starttime_3;
public string starttime_4;
public string starttime_5;
public string starttime_6;
public string endtime_1;
public string endtime_2;
public string endtime_3;
public string endtime_4;
public string endtime_5;
public string endtime_6;
I would strongly suggest changing your variable types to DateTime?. It is better to store data in its native type and then do the convert to string on display. This way, when you want the duration, you are not parsing back to DateTime. You can handle any rounding you want on the base data.
So, your conversion to string should be at the highest level of you stack. It will keep your code cleaner and make it easier to refactor the logic away from the UI later if appropriate.
Not really sure I understand all this parsing but if you're just trying to record start and stop times and output a timespan I would do as Jon Skeet recommend with the stopwatch. Something along these lines looks like what you're going for but a bit cleaner.
// Build stopwatch and lists
Stopwatch sw = new Stopwatch();
List<string> startTimes = new List<string>();
List<string> endTimes = new List<string>();
private void startBtn_Click(object sender, EventArgs e)
{
// Start stopwatch and record start time
sw.Start();
startTimes.Add(DateTime.Now.ToString("h.mm"));
}
private void stopBtn_Click(object sender, EventArgs e)
{
// Stop stopwatch
sw.Stop();
// Record stop time and reset stopwatch
endTimes.Add(DateTime.Now.ToString("h.mm"));
sw.Reset();
// Output timespan
outputLbl.Text = sw.Elapsed.ToString();
}
Related
I'm trying to get specific data from an .ini file and display it in GridView. The .ini file is updated with information from the last cut a saw made, and every time the file is updated I want the new information displayed in a new row. The problem I keep running into is that the method I have for populating the grid viewer is repeating once every time the file is changed. Sometimes it displays the correct information twice, and sometimes it displays incorrect information once, and then the second time the correct information is displayed.
I added a check using a bool variable to try to stop this, but that hasn't stopped it from outputting twice.
using System.Text.RegularExpressions;
namespace outputViewer
{
public partial class outputViewer : Form
{
//Declare variables for filepath and create a new dictionary
private string iniFilePath;
private string vjob = "";
private string vpart = "";
private string vname = "";
private string vlength = "";
private string vwidth = "";
private string vheight = "";
private string vgrade = "";
private string vcenterLine = "";
bool populate = false; //If PopulateIniDataGrid has been called turn true
public outputViewer()
{
InitializeComponent();
}
//Watch .ini file for changes
public void Watch()
{
var watcher = new FileSystemWatcher(Path.GetDirectoryName(iniFilePath), Path.GetFileName(iniFilePath))
{
EnableRaisingEvents = true,
NotifyFilter = NotifyFilters.LastWrite
};
watcher.Changed += OnFileChanged;
}
//On file change reset bool variable and call ReadIniFile method
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
populate = false;
ReadIniFile();
}
//Reads .ini file using WriteSafeReadAllLines Method, and extracts data for Output
private void ReadIniFile()
{
var iniFileLines = WriteSafeReadAllLines(iniFilePath);
var currentSection = "";
foreach (var line in iniFileLines)
{
//Code sorting through data for output
}
//Check if PopulateIniDataGridView has been called
if (!populate)
{
PopulateIniDataGridView();
populate = true;
}
}
//Set filepath of .ini file
private void setFilePathToolStripMenuItem_Click(object sender, EventArgs e)
{
//Create new openFileDialog object
var openFileDialog = new OpenFileDialog
{
//File type filters for openFileDialog and set default directory to MyDocuments
Filter = "INI files (*.ini)|*.ini|All files (*.*)|*.*",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
//If Successful
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
iniFilePath = openFileDialog.FileName;
selectedIniFileLabel.Text = iniFilePath;
}
Watch();
}
//Convert method converts mm to feet-inches-sixteenths
private void Convert(ref string imperial)
//Allow reading file when open by another application
public string[] WriteSafeReadAllLines(string path)
private void PopulateIniDataGridView()
{
//Convert metric to imperial
Convert(ref vwidth);
Convert(ref vheight);
Convert(ref vlength);
Convert(ref vcenterLine);
Invoke(new MethodInvoker(delegate
{
scOutputGridView.Rows.Add(vjob, vname, vpart, vlength, vwidth, vheight, vgrade);
}));
}
}
}
PROBLEM: weather.txt contains weather information for every day in January 2018. Each line is formated:
"Date;Precipitation;HighTemp;LowTemp"
1/1/2018;0;29;10
Split and tokenize each line and display data for the date picked in Form Labels.
The problem I'm having is how to check the tokenized DateTime data to see if it matches the DateTime picked from the DateTimePicker so that I can display the correct information in the labels.
Labels in form to hold corresponding data: dateLabel, precipLable, highLabel, lowLabel.
namespace WeatherData2
{
struct WeatherData
{
public DateTime date;
public double precip;
public int highTemp;
public int lowTemp;
}
public partial class Form1 : Form
{
private List<WeatherData> weatherList = new List<WeatherData>();
public Form1()
{
InitializeComponent();
}
private void ReadFile()
{
try
{
StreamReader inputFile;
string line;
WeatherData entry = new WeatherData();
char[] delim = { ';' };
inputFile = File.OpenText("weather.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
DateTime.TryParse(tokens[0], out entry.date);
double.TryParse(tokens[1], out entry.precip);
int.TryParse(tokens[2], out entry.highTemp);
int.TryParse(tokens[3], out entry.lowTemp);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
}
}
If any clarification is need, please let me know. I probably wrote that 10 kinds of confusing. Any help would be greatly appreciated. Thanks.
You can use linq to easily check:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
var pickedDate = dateTimePicker1.Value.ToShortDateString();
if (weatherList.Any(e => e.date == pickedDate))
{
var matching = weatherList.First(e => e.date == pickedDate);
}
}
you also need to make some changes to your loop. right now you are overwriting your entry object for each iteration of the loop and not adding it to you collection.
while (!inputFile.EndOfStream)
{
//create a new instance of entry for each iteration
entry = new WeatherData();
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
DateTime.TryParse(tokens[0], out entry.date);
double.TryParse(tokens[1], out entry.precip);
int.TryParse(tokens[2], out entry.highTemp);
int.TryParse(tokens[3], out entry.lowTemp);
//add the item to the list
weatherList.Add(entry);
}
Here is my code when click a button in C# WinForm:
private void aesactive_Click(object sender, EventArgs e)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Reset();
stopWatch.Start();
string original = textBox4.Text;
using (var random = new RNGCryptoServiceProvider())
{
string inputkey = textBox5.Text;
byte[] key = Encoding.ASCII.GetBytes(inputkey);
random.GetBytes(key);
byte[] encrypted = EncryptStringToBytes_Aes(original, key);
}
stopWatch.Stop();
textBox6.Text = stopWatch.ElapsedMilliseconds.ToString() + " ms ";
}
But when I click that button twice, or more, the results always 0 ms. Can anybody explain to me the reasons ? Thanks a lot.
If you would like to accumulate time, move Stopwatch variable outside the method, and remove the call to Reset():
private readonly Stopwatch stopWatch = new Stopwatch();
private void aesactive_Click(object sender, EventArgs e) {
stopWatch.Start();
...
stopWatch.Stop();
textBox6.Text = stopWatch.ElapsedMilliseconds.ToString() + " ms ";
}
Now that adding time is a "one-way street," consider adding a button to reset the stopwatch:
private void aesreset_Click(object sender, EventArgs e) {
stopWatch.Reset();
}
Note: Modern CPUs are capable of running millions instructions per millisecond, so it may require you to click the button many times for the value in textBox6 to move off zero.
I'm writing a program that has multiple event handlers in it, new territory for me. One event handler watches a folder and when a file is moved into it it opens the file, gets one piece of information out of the file, stores that data in a list of objects and then moves the file to another folder. The second event handler is based off of a timer where it's interval is set for 10 seconds. When the timer elapses it loops through the list I've loaded up and checks to see if the timestamp of when the item was loaded to the list is more than 1 minute old and if it is then it just displays a message to the console. I have two main problems: first) the message that should be displayed to the console once a minute is displaying more often than it should (about once every 15 seconds as opposed to once a minute) and 2) when I try to debug the program and it gets to the timer event handler it jumps all over the place that doesn't follow any logical path to me (I'm probably wrong). Please, can someone help me out? Any help would be much appreciated.
Code:
public class fileObject
{
public string strPONumber { get; set; }
public DateTime dtArrival { get; set; }
}
private static System.Timers.Timer aTimer;
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
Console.WriteLine("redefined");
List<fileObject> lstPONums = new List<fileObject>();
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = #"C:\Users\z088476\Desktop\FolderA\";
// Only watch text files.
watcher.Filter = "*";
// Add event handlers.
Console.WriteLine("before event");
watcher.Created += new FileSystemEventHandler((sender, e) => OnChanged(sender, e, lstPONums));
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler((sender, e) => OnTimedEvent(sender, e, lstPONums));
aTimer.Interval=10000;
aTimer.Enabled = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e, List<fileObject> lstPONumbers)
{
fileObject fObj = new fileObject();
string strLine = "";
using (StreamReader sr = new StreamReader(e.FullPath))
{
strLine = sr.ReadLine();
}
string strDelim = strLine.Substring(3,1);
List<string> lstSplit = new List<string>();
lstSplit = strLine.Split(Convert.ToChar(strDelim)).ToList();
fObj.strPONumber = lstSplit[30];
fObj.dtArrival = DateTime.Now;
lstPONumbers.Add(fObj);
File.Move(e.FullPath, #"C:\Users\z088476\Desktop\FolderC\" + e.Name);
}
private static void OnTimedEvent(object source, ElapsedEventArgs e, List<fileObject> lstPONumbers)
{
if (lstPONumbers.Count != 0)
{
foreach (fileObject fo in lstPONumbers)
{
DateTime dtnow = DateTime.Now;
TimeSpan duration = DateTime.Now - fo.dtArrival;
if (duration.TotalMinutes > 1)
{
Console.WriteLine("IT IS MORE THAN 1 MIN!!!!");
}
}
}
}
Firstly, apologies for asking a question that has been asked before, but even with the examples I am not getting the desired results.
All I am trying to do is display the current time, which it does, but I noticed that the datetime format was 9:5:6 instead of 09:05:06. I read the examples about formatting DateTime but it doesn't work for some reason. Can anyone shed any light on where I am going wrong?
Thanks for your help as always.
public MainWindow()
{
InitializeComponent();
DispatcherTimer dispatchTimer = new DispatcherTimer();
dispatchTimer.Tick += new EventHandler(dispatchTimer_Tick);
dispatchTimer.Interval = new TimeSpan(0, 0, 1);
dispatchTimer.Start();
}
private void dispatchTimer_Tick(object sender, EventArgs e)
{
var hour = DateTime.Now.Hour.ToString();
var min = DateTime.Now.Minute.ToString();
var sec = DateTime.Now.Second.ToString();
var today = hour + ":" + min + ":" + sec;
label1.Content = today;
textBlock1.Text = today;
button1.Content = today;
}
Just use a custom format string:
var today = DateTime.Now.ToString("HH:mm:ss");
Or the standard one:
var today = DateTime.Now.ToString("T");
string now = DateTime.Now.ToString("HH:mm:ss");
Check TimeZoneInfo Class for more detailed globalization.
I think there are many ways to tackle this issue.
Personally, and to keep things simple, I would do it this way:
private void dispatchTimer_Tick(object sender, EventArgs e)
{
string wTime = DateTime.Now.ToString("HH:mm:ss");
// OR THIS WAY
string wTime2 = DateTime.Now.ToString("T");
label1.Content = wTime;
textBlock1.Text = wTime;
button1.Content = wTime;
}
But if you want for some reasons to keep your initial logic then this would do it too.
private void dispatchTimer_Tick(object sender, EventArgs e)
{
string hour = DateTime.Now.Hour.ToString("00");
string min = DateTime.Now.Minute.ToString("00");
string sec = DateTime.Now.Second.ToString("00");
var today = hour + ":" + min + ":" + sec;
label1.Content = today;
textBlock1.Text = today;
button1.Content = today;
}
You may also wish to look at this http://msdn.microsoft.com/en-us/library/az4se3k1.aspx