Play Audio File If Time Matches - c#

Why can't I get this audio file played when the time in textboxordertostart.Text in string format equals the system time? Textboxordertostart gets time after subtracting minutes from DateTimePicker time.
My code is as follow.
SoundPlayer myplayer = new SoundPlayer();
myplayer.SoundLocation= (#"c:\users\woolsvalley\documents\visual studio 2015\Projects\WindowsFormsApplication17\WindowsFormsApplication17\Alarm.wav");
if (DateTime.Now.ToString("hh:mm tt") == textBox_ordertostart.Text)
{
myplayer.Play();
}
This code throws a null exception
string formatString = "yyyHHmmss";
string sample = textBox_ordertostart.Text;
DateTime dt = DateTime.ParseExact(sample, formatString, null);
if (DateTime.Now == dt)
{ myplayer.Play(); }
this is not working as well
if (DateTime.Now == DateTime.Parse(textBox_ordertostart.Text))
{ myplayer.Play(); }

The way you're doing the comparison is a very "brittle" way of doing the comparison because it's dependent on the user typing the time in the exact format you're expecting it in. For example, when I tested this, I got the following results:
string datetime = DateTime.Now.ToString("hh:mm tt");
// False
Console.WriteLine(datetime == "2:06 PM");
// False
Console.WriteLine(datetime == "2:06 P.M.");
// False
Console.WriteLine(datetime == "2:06");
// False
Console.WriteLine(datetime == "02:06 P.M.");
// True
Console.WriteLine(datetime == "02:06 PM");
If you parse it to a DateTime object and then do ToString, it'll be less brittle though. See this extension method, for example:
public static bool DayMinuteEqual(this string otherDate)
{
// We have to strip out the "." character if present (e.g. 2:05 P.M.)
DateTime otherDateObj = DateTime.Parse(otherDate.Replace(".", ""));
return DateTime.Now.ToString("hh:mm tt") == otherDateObj.ToString("hh:mm tt");
}
Now I get the results I expect:
// True
Console.WriteLine("2:20 PM".DayMinuteEqual());
// True
Console.WriteLine("2:20 P.M.".DayMinuteEqual());
// False, but we'd expect it due to the omission of the "P.M."
Console.WriteLine("2:20".DayMinuteEqual());
// True
Console.WriteLine("02:20 P.M.".DayMinuteEqual());
// True
Console.WriteLine("02:20 PM".DayMinuteEqual());
Clearly, then, this much less dependent on the user entering the date in a "perfect" format (but still requires them to have some sense of the correct format).

thanks guys. This code works i just needed to raise it in the updating event.
private void timer1_Tick(object sender, EventArgs e)
{ label_time1.Text = DateTime.Now.ToString("hh:mm tt");
mplayer = new SoundPlayer();
mplayer.SoundLocation = (#"c:\users\woolsvalley\documents\visual studio 2015\Projects\WindowsFormsApplication17\WindowsFormsApplication17\Alarm.wav");
if((DateTime.Now.ToString("HH:mm tt") == ((textBox_ordertostart.Text))))
{ mplayer.Play(); }

Related

Using C# How can I parse this string to a Time

I have a C# Visual Studio web application that uses Telerik RadTimePickers to collect the start time and end times, formatted as 24 hour time. These two elements get stored in the database as a string formatted as 09:00:00-09:30:00.
Now when the application retrieves the data from the database I need to convert that string into 2 separate times, in the 24 hour format, so I can use those values as the Selected Time for the RadTimePickers.
I use the code below to extract the two dates from the string;
if (Results.TimeOfDay != "-" || Results.TimeOfDay != null)
{
string[] times = Results.TimeOfDay.Split('-');
string time1 = times[0];
RadTimePicker1.SelectedTime = ParseTime(time1);
string time2 = times[1];
RadTimePicker2.SelectedTime = ParseTime(time2);
}
The Code for ParseTime looks like this:
static public TimeSpan ParseTime(string input)
{
TimeSpan output;
var ok = TimeSpan.TryParseExact(input, #"hh\:mm\:tt", CultureInfo.InvariantCulture,out output);
return output;
}
But it is not working, the var ok value returns false and the output value is 1/1/0001 12:00:00 AM.
New to C# and cannot figure out how to fix this problem. Can someone help please
Based on comments I changed the code to parse to this
static public TimeSpan ParseTime(string input)
{
TimeSpan output;
var ok = TimeSpan.TryParseExact(input, #"hh\:mm\:tt", CultureInfo.InvariantCulture,out output);
return output;
}
if (Results.TimeOfDay != "-" || Results.TimeOfDay != null)
This will always be true, because you are asking if .TimeOfDay, or "09:00:00-09:30:00", is not equal to "-". You should use Results.TimeOfDay.Contains("-") instead.
Also,
#"h:mm tt"
This should be #"hh:mm:tt"
Edit: sorry should be #"hh\:mm\:ss"
You can just parse it as a TimeSpan with the following code
TimeSpan.TryParseExact(input, #"hh\:mm\:ss", CultureInfo.InvariantCulture, out output);
Note for TimeSpan you have to use hh rather than HH for DateTime and you have to delimit the colons.
Note you really should also check the return of TryParseExact and do something to handle when the input does not match the format. Otherwise the resulting output will be the default for TimeSpan which is 00:00:00
As other's have mentioned if (Results.TimeOfDay != "-" || Results.TimeOfDay != null) will always be true. If you change it to if (Results.TimeOfDay != "-" && Results.TimeOfDay != null) then you'll skip the parsing when TimeOfDay is null or equal to "-". Although you really should handle all the error cases which would be TimeOfDay is null, TimeOfDay does not contain a - or contains multiples and when the values on each side of the - are not formatted correctly.

C# Check if input is valid date

I am working on a calendar. And here I want to check if the users input is a date and if it's not showing an error. I heard about DateTime.TryParse. How can I use this here properly? Can maybe anyone explain it in simple words?
public void addMeeting()
{
string readAddMeeting;
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}; // I copied this
Console.WriteLine("Add a schedule for specific dates: ");
readAddMeeting = Console.ReadLine();
}
Use DateTime.TryParseExact in this way:
public void addMeeting()
{
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"};
Console.WriteLine("Add a schedule for specific dates: ");
string readAddMeeting = Console.ReadLine();
DateTime scheduleDate;
bool validDate = DateTime.TryParseExact(
readAddMeeting,
dateFormats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None,
out scheduleDate);
if(validDate)
Console.WriteLine("That's a valid schedule-date: {0}", scheduleDate.ToShortDateString());
else
Console.WriteLine("Not a valid date: {0}", readAddMeeting);
}
The method returns a bool indicating whether it could be parsed or not and you pass a DateTime variable as out parameter which will be initialized if the date was valid.
Note that i'm using DateTimeFormatInfo.InvariantInfo because you don't want to use the local DateTime format but one that works in any culture. Otherwise the / in dd/MM/yyyy would be replaced with your current culture's date separators. Read
Even if it sounds a bit brutal, but it seems ike you should do some readup on arrays/lists, foreach loops and DateTime.TryParse.
That aside you have different possible date formats and want to see if one of them is valid. If we take the example from the msdn homepage for tryparse https://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx and use foreach it becomes quite easy:
public void addMeeting()
{
string readAddMeeting;
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}; // I copied this
bool isDateOk = false;
Console.WriteLine("Add a schedule for specific dates: ");
readAddMeeting = Console.ReadLine();
foreach (string myDateFormat in dateFormats)
{
DateTime dateValue;
if (DateTime.TryParse(readAddMeeting, dateValue))
{
isDateOk = true;
}
}
if (isDateOk == false)
{
Console.Writeline("Sorry this is not a valid date");
}
}

using C# to make an algorithm to understand 00/00/00

I am writing C# code for a business rule in a program called Prophet 21.
The code essentially is saying, if a product price has been updated in the last year, put that price into a field called PO Price.
Everything works solid except for one tiny problem, when making sure that the price was updated within the last year, it looks at the PO Price update date. At some point in the past, a lot of these were set to 00/00/00 and using an algorithm with date doesn't seem to understand it. My best guess is that I need to convert the date somehow, but I am quite a C# novice, any help would be appreciated. Here's the code I am working with.
public class SetPOCost : Rule //this rule sets the PO cost to the other cost when the item is stockable and the disposition is B
{
public override RuleResult Execute()
{
RuleResult result = new RuleResult();
result.Success = true;
string s = Data.Fields["other_cost"].FieldValue;
decimal ldcOtherCost = Convert.ToDecimal(s);
s = Data.Fields["po_cost"].FieldValue;
decimal ldcPOCost = Convert.ToDecimal(s);
string stockable = Data.Fields["stockable"].FieldValue;
string disposition = Data.Fields["disposition"].FieldValue;
s = Data.Fields["ufc_inventory_supplier_date_cost_last_modified"].FieldValue;
//this next line is added from the SuggestPromiseDate rule because it was running into errors doing both rules
Data.Fields.GetFieldByAlias("suggested_promise_date").FieldValue = Data.Fields.GetFieldByAlias("line_max_promise_date").FieldValue;
DateTime dtLastModified = Convert.ToDateTime(s);
DateTime thisDate = DateTime.Today;
DateTime thisDateLastYear = thisDate.AddYears(-1);
Boolean dateIsGood = dtLastModified.CompareTo(thisDateLastYear) >= 0;
if (stockable == "N" && disposition == "B" && ldcPOCost == 0 && ldcOtherCost > 0 && dateIsGood)
{
Data.Fields["po_cost"].FieldValue = ldcOtherCost.ToString();
}
return result;
}
You can use TryParse to check the date coming in.
s = Data.Fields["ufc_inventory_supplier_date_cost_last_modified"].FieldValue;
//this next line is added from the SuggestPromiseDate rule because it was running into errors doing both rules
Data.Fields.GetFieldByAlias("suggested_promise_date").FieldValue = Data.Fields.GetFieldByAlias("line_max_promise_date").FieldValue;
DateTime dtLastModified;
if (DateTime.TryParse(s, out dtLastModified) == false)
dtLastModified = DateTime.MinValue;
How about just:
s = Data.Fields["ufc_inventory_supplier_date_cost_last_modified"].FieldValue;
if (s == "00/00/00") {
s="01/01/0001";
}
00/00/00 is not a valid date in .NET; dates start counting from January 1st, 0001. Detect when this date occurs in your original data source, and then create a new date as new DateTime(0);.

Convert string into datetime in razor view with javascript?

In my controller I convert the datetime into string
here's the code
var result = from c in displayedCustomers select new[] { c.NonActiveDate.ToString("dd-MM-yyyy HH:mm:ss")};
and I want to convert it back to datetime cause I want to compare it with today date
this is my code and not working cause the string cannot be compare with date
if (d <= Date.now)
{
return '<span style = "color : red">' + oObj.aData[4]+ '</span>';
}
Convert your string to Date object in java script using "Date" function before comparing
if(new Date("your date string") <= Date.now)
{
// your code
}
cant you fill another string with the date time now and compare them that way.
{
var time = DateTime.Now;
string Time = time.ToString();
if(yourtimevariable == Time)
{
//enter what you want to do when the if statement is true
}
}

how to Check datetime entered

I have a textBox where the user enters a datetime using a calendar, I am checking for whether the text box is empty or not by
if ((string.IsNullOrEmpty(txt_SendAt.Text) == false)
How can I check whether the datetime entered is less or = to the current datetime
if ((string.IsNullOrEmpty(txt_SendAt.Text) == false
&& DateTime.Parse(txt_SendAt.Text) <= DateTime.Now )
DateTime enteredDateTime;
if (!DateTime.TryParse(txt_SendAt.Text, out enteredDateTime))
{
Debug.WriteLine("User entered date time in wrong format");
}else
{
if(enteredDateTime <= DateTime.Now)
{
// less or equal
}
}
Parse or TryParse the text to DateTime, then compare to DateTime.Now
A few steps here, first check something is entered, as you have done, secondly, check it is actually a date, and lastly check against the desired date, as such:
var input = DateTextBox.Text;
if (!string.IsNullOrEmpty(input))
{
DateTime date;
if (DateTime.TryParse(input, out date))
{
if (date <= DateTime.Now)
{
//bingo!
}
}
}
Notice the TryParse for checking proper formatting of the input string as a date - using only Parse is a sure way to make your app go BANG!
You can parse your string input to a DateTime using the DateTime.Parse method, then run your comparison in the normal way.
Remember, Parse methods will throw a FormatException if the input is not directly castable to the required type. It may make more sense to go for the TryParse method if you have, for example, a free-text input.
var inputDate = DateTime.Parse(txt_SendAt.Text);
if (inputDate > DateTime.Now)
{
Console.WriteLine("DateTime entered is after now.");
}
else if (inputDate < DateTime.Now)
{
Console.WriteLine("DateTime entered is before now.");
}
Use one of the Parse or TryParse static methods of the DateTime class to convert the string to a DateTime and compare it to the current DateTime.
DateTime input;
if(DateTime.TryParse(txt_SendAt.Text,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out input))
{
if(input <= DateTime.Now)
{
// your code here
}
}
else
{
//not a valid DateTime string
}
if (!(string.IsNullOrEmpty(txt_SendAt.Text) && Datetime.Parse(txt_SendAt.Text)<=Datetime.Now)
{
/*code */
}
else
{
/*code */
}

Categories

Resources