Label Display Integer - c#

I'm making a alarm clock in my application and the code requires me to set a variable int from a combo box into my program.
if ((e.Result.Text == "set a alarm") || (e.Result.Text == "set an alarm"))
{
Jarvis.Speak("setting alarm");
label2.Content = DateTime.Today.Hour.ToString(HourAlarmCB) + ":" + DateTime.Today.Minute.ToString("54") + ":" + DateTime.Today.Second.ToString("00");
label2.Opacity = 100;
dispatcherTimer2.Start();
}
The HourAlarmCB is the ComboBox with content in it "1","2", etc. but the error wont allow me to use ToString, is there any way around this?

I believe that you may be incorrectly making use of ToString().
Are you trying to retrieve the following formatted result?
hh:mm:ss
If so, you might find this approach worthy of consideration:
int hour = Convert.ToInt32(HourAlarmCB.SelectedItem);
int minute = DateTime.Today.Minute;
int second = DateTime.Today.Second;
label2.Content = String.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);
See String.Format for converting an arbitrary list of variables into a single formatted string.
For a description of "D2", see Standard Numeric Format Strings.
Update: First, note that DateTime.Today returns "an object that is set to today's date, with the time component set to 00:00:00."
Now, in reference to your question, to output AM or PM, use the t standard format string:
DateTime date = DateTime.Today; // time is '00:00:00'
int hour = Convert.ToInt32(HourAlarmCB.SelectedItem);
int minute = date.Minute; // always '0'
int second = date.Second; // always '0'
label2.Content = String.Format("{0:D2}:{1:D2}:{2:D2} {3:t}",
hour, minute, second, date); // for example: '08:00:00 AM'

So the end result is me having to the HourAlarmCB variable to a string
if ((e.Result.Text == "set a alarm") || (e.Result.Text == "set an alarm"))
{
Jarvis.Speak("setting alarm");
string HourAlarmStr = HourAlarmCB.SelectedItem.ToString();
label2.Content = DateTime.Today.Hour.ToString(HourAlarmStr) + ":" + DateTime.Today.Minute.ToString("54") + ":" + DateTime.Today.Second.ToString("00");
label2.Opacity = 100;
dispatcherTimer2.Start();
}

Related

How to concatinate customize School Year in C#

Can someone help me please?
I have a program where I can add multiple entries of School Year. The primary ID format should be i.e. SY17-18, SY18-19, and so on. I did get the format but I am using DateTime.Now to get the current year hence the primary ID would stay the same everytime I run the program since I am basing it on the DateTime.
Here is my code:
int curr = Convert.ToInt32(DateTime.Now.ToString("yy"));
int dt = curr + 1;
string sy = "SY" + curr + "-" + dt;
txtSYID.Text = sy;
How can I able to produce this kind of format where it automatically concatenate without having to based in the current year.
Thank you for your help.
If Current DateTime shows 2018/10 then we are in SY18-19 however 2019/3 is still SY18-19 ( I have set the 6th month as the end of the school year however you can change it it was only to set an example):
DateTime date = DateTime.Now;
int curr = date.Year;
if(date.Month <= 6) curr--;
string sy = $"SY{curr}-{curr + 1}";
Edit (considering your comment):
If you want to generate school years only you can do this (you dont need datetime):
Enumerable.Range(17, 50).Select(x=> $"SY{x}-{x+1}").ToArray();
the above code will give you an array containing school year up to SY50-51.
if you want it in a comma separated string:
for(int i=17;i<50;i++)
sy += $",SY{i}-{i+1}";
sy = sy.SubString(1);
public string ToFinancialYearShort(DateTime dateTime)
{
return "SY: " + (dateTime.Month >= 4 ? (dateTime.ToString("yy")
+ " - " +dateTime.AddYears(1).ToString("yy")) : (dateTime.AddYears(-1).ToString("yy") + " - " + dateTime.ToString("yy")));
}
This Should work

c# convert PDF metadata CreationTime to DateTime

I need to process the CreationTime I retrieve from the PDF's metadata and compare it to DataTime format.
string path = e.Row.Cells[1].Text;
var pdfReader = new PdfReader(path);
var CreatedDate = pdfReader.Info["CreationDate"];
e.Row.Cells[13].Text = Convert.ToString(CreatedDate);
This returns a Date-Time-String like:
D:20150710080410
D:20150209075651+01'00'
and to compare:
DateTime Created = Convert.ToDateTime(CreatedDate);
DateTime Compare = Convert.ToDateTime(e.Row.Cells[14].Text);
if (Compare > Created)
{
e.Row.Cells[15].Text = "actualizar";
}
Martin
I really needed a solution for this, BBL Admin 's Comment on writing your own function turned out to be my way out.
From this [this itex support link][1] I was able to get the intepratation of the pdfDate format as D:YYYYMMDDHHmmSSOHH'mm'
Next thing I needed to know is the supportade date formats in c# that I may Parse using DateTime.Parse() from [this c-sharpcorner artical][2] and the most ideal for me was "yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss"
Having known the input I get and the format I can parse, I created the function below to construct the date, basically getting parts from the pdfDate and building parts for the 'parsable' date string...
private DateTime CreateDateTime(string date) //use the pdfDate as parameter to the date argument
{
string dateStr = date.Remove(0, 2).Remove(14, 6); //Remove D: & OHH'mm
string tmpDateStr = dateStr.Substring(0, 4) //Get year i.e yyyy
+ "-" + dateStr.Substring(4, 2) // Get month i.e mm & prepend - (hyphen)
+ "-" + dateStr.Substring(6, 2) // Get day i.e dd & prepend -
+ "T" + dateStr.Substring(8, 2) // Get hour and prepend T
+ ":" + dateStr.Substring(10, 2) // Get minutes and prepend :
+ ":" + dateStr.Substring(12, 2); //Get seconds and prepend :
return DateTime.Parse(tmpDateStr);
}
Well, I hope you found a way at the time of asking, anyone else facing the same challange could try my approach and see if it helps. Nevertheless, question answered.
NB: There could be other/better ways to do it.
[1]: http://itextsupport.com/apidocs/iText7/7.1.0/com/itextpdf/kernel/pdf/PdfDate.html
[2]: https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1
If your Date-Time string that you're trying to convert is going to start with "D:" every time, then you might think about adding in a remove function for D:. That's what's probably giving you the exception when you try to convert. Try this:
// Gather the Info
string path = e.Row.Cells[1].Text;
var pdfReader = new PdfReader(path);
var CreatedDate = pdfReader.Info["CreationDate"];
e.Row.Cells[13].Text = Convert.ToString(CreatedDate);
string sCreatedDate = Convert.ToString(CreatedDate).Remove(0, 2)
// Convert and Compare
DateTime Created = Convert.ToDateTime(sCreatedDate);
DateTime Compare = Convert.ToDateTime(e.Row.Cells[14].Text);
if (Compare > Created)
{
e.Row.Cells[15].Text = "actualizar";
}
You don't have to create sCreatedDate, but it's a little bit cleaner to view it that way. You could also convert CreatedDate.ToString().Remove(0,2) when you do the datetime convert:
DateTime Created = Convert.ToDateTime(CreatedDate.ToString().Remove(0,2));
Hope this helps.

dateTimePicker1.Value < dateTimePicker2.Value = true when values are identical on runtime

I have dateTimePicker1 and dateTimePicker2 controls loading on Form1. They both have the same date and time on load.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy-MM-dd hh:mm:ss";
dateTimePicker2.Format = DateTimePickerFormat.Custom;
dateTimePicker2.CustomFormat = "yyyy-MM-dd hh:mm:ss"
When I check if they have different values using
if (dateTimePicker1.Value < dateTimePicker2.Value) {
Console.WriteLine(dateTimePicker1.Value + " is earlier than " + dateTimePicker2.Value);
}
the statement returns true and writes to the console. This is not what I would expect. I would expect this to return false.
If I increase each control's value by 1 second, causing them to still match, the statement returns false as expected and nothing is written to the console.
Why does the less than evaluation return true on load when both values are identical?
Do not know how you are loading the values. But, depending on what precision you are looking for (eg. in hours, minutes or second) you can subtract the two values and compare. Example: If you need precision in seconds then you can do something similar to below:
dateTimePicker1.Value = DateTime.Now;
dateTimePicker2.Value = DateTime.Now.AddMilliseconds(999);
var timeSpan1 = dateTimePicker1.Value - dateTimePicker2.Value;
if (Math.Abs(timeSpan1.TotalSeconds) > 1) {
MessageBox.Show(dateTimePicker1.Value + " is not same as " + dateTimePicker2.Value);
} else {
MessageBox.Show(dateTimePicker1.Value + " is same as " + dateTimePicker2.Value);
}
The answer is given by setting the two values equal to each other on load. This is because the controls load at different times. They are not really equal.
private void Form1_Load(object sender, EventArgs e)
{
dateTimePicker2.Value = dateTimePicker1.Value;
}
I'm not sure how to give credit here, it belongs to two commenters.

how to enter valid date in database for separate date month year

I have a registration form in my project on which I used three dropdownlists to enter day, month and year. In this date added to dropdownlist by codebehind method:
private void Add_Date()
{
ddl_dat.Items.Add(new ListItem("-Date-", "-1"));
for (int j = 0; j < 31; j++)
{
var newOption = new ListItem("" + (j + 1).ToString(), j.ToString());
ddl_dat.Items.Add(newOption);
}
}
And I add 12 months manually in month dropdownlist. I want user don't able to enter 29 feb or 31 april.
I done this by appling check before submitting the form:
if (ddl_year.SelectedIndex != -1 && ddl_dat.SelectedIndex != -1 && ddl_mon.SelectedIndex != 0)
{
if (ddl_mon.SelectedIndex == 2 && ddl_dat.SelectedIndex >= 28)
{
lbl_alert.Text = Convert.ToInt32(ddl_dat.SelectedValue)+ 1 + " Febuary Doesn't Exist";
}
}
Same method for all other months . But I don't think this is the correct method to solve this problem. Does anyone have any suggestions?
Apply this check before submitting form:
string str = ddl_dat.SelectedValue + "/" + ddl_mon.SelectedValue + "/"
+ ddl_year.SelectedValue;
DateTime dt;
if(!DateTime.TryParse(str, out dt))
// Invalid date - Show error
else
// Use date from dt here
If date is invalid TryParse will return false. Else you can use the resulting date from dt variable for further operation.
Since this is ASP.NET, you can use UpdatePanel to dynamically fill the contents of Date combobox on-the-fly through AJAX. You could then use DateTime.DaysInMonth() to find out the exact number of days in a month. You should update your Date combobox on both month and year dropdown's SelectedIndexChanged. This way your user won't be able to select incorrect dates in the first place, so no need to handle any errors.
Alternately there is Javascript calendar available in JQuery that could make your life easier.
DateTime.TryParse should help you.
DateTime dateValue;
string dateString = ddl_year.SelectedValue + "-" + ddl_mon.SelectedValue + "-" + ddl_dat.SelectedValue;
if (! DateTime.TryParse(dateString, out dateValue)) {
//Error...
}

How can a string timestamp with hours 0 to 24 be parsed

I am trying to parse a string timestamp of format "yyyyMMddHHmmss" with DateTime.ParseExact(). The catch is I must allow for an hour value of "24" (i.e. hours can be from 0 to 24, where hour 24 denotes hour 0 of the next day (day + 1, hour = 0) Note: I can't control the input values.) and, of course, that results in an exception.
Are there any settings/properties I can set instead of manually parsing/using regex's? If not, any efficient parsing ideas?
ex.
DateTime.ParseExact("20120911240000", "yyyyMMddHHmmss",
System.Globalization.CultureInfo.InvariantCulture);
if you want to do it manually you can use String.Substring() to detect hour values of "24", then use String.Replace, to set that to "00", then parse your date, and then add a day if that's what an hours value of "24" means
Sam's solution is good, but since you are using yyyyMMddHHmmss I would do something like:
bool addDay = false;
DateTime result;
string dtToParse = "20120911240000";
if (dtToParse[8] == '2' && dtToParse[9] == '4')
{
dtToParse = dtToParse.Substring(0, 8) + "00" + dtToParse.Substring(10);
addDay = true;
}
result = DateTime.ParseExact(dtToParse, "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
if (addDay) { result = result.AddDays(1); }
There is no simple flag to do what you want.
However, here is the way to create custom datetime parser:
How to create and use a custom IFormatProvider for DateTime?

Categories

Resources