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
Related
I am trying to select items from a database where their date equals the date in the Session. It says there is no row at position [0][2], but there is actually a row there. This is my code:
DateTime b = Convert.ToDateTime(Session["Dat"]);
int D = b.Day;
int M = b.Month;
int Y = b.Year;
string dat = M + "/" + D + "/" + Y ;
DataTable m;
m = DAL.SelectFromTable(
"SELECT * FROM [ToDoList] where [UserID]='" + k + "' and [D]="+ dat);
if (m.Rows.Count > 0)
{
Response.Write("</br></br></br><center>" + m.Rows[0][2].ToString() + "</center>");
}
Access requires dates to be surrounded by #.
Assuming DAL is not written by you, and you don't really have the option to correctly and securely query the database, you would have to do something like:
...and [D] = #" + dat + "#"
However, #thisextendsthat has good point that this will probably return no results because you would have to have the time portion of the date exactly as the data is in the database and you are only using month, day and year to build the date.
You could also get around the time portion by selecting a range:
... and [D] BETWEEN #" + dat + "# AND #" + // one day greater than your date at midnight + "#"
But if you do that you have to be careful not to create an impossible date like May 32, for instance.
Be sure to thank your teacher for continuing to train students to code insecurely, keeping SQL injection vulnerabilities right at the top of the OWASP top 10, right where it belongs.
There is no reason to reinvent the wheel, just use method ToString:
DateTime b = Convert.ToDateTime(Session["Dat"]);
DataTable m;
m = DAL.SelectFromTable("select * from [ToDoList] where [UserID] = '" + k + "' and [D] = #" + dat.ToString("yyyy'/'MM'/'dd") + "#");
As Crowcoder says, which DB are you using? That will help determine how you ought to be sending dates into your queries.
If the underlying field is a datetime then you may need to explicitly trim the time part from the value in order to compare to a date. In Sql server:
...where CAST([D] as DATE) = [The date passed in from from C#]
Otherwise you might be comparing today at some arbitrary time to today at midnight, which won't give you what you want.
Also, please think think about paramterising your Sql queries - building up a string literal like this is bad practice and leaves your app vulnerable to Sql injection attacks.
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.
I need to convert
20141013T155544.673-04/0
To a DateTime type.
Presently I am manually parsing the string out
//20130605T154727.683-04/0
//20130806T143808.018-04
//var a = new DateTime();
var year = segmentDate[0].ToString(CultureInfo.InvariantCulture) + segmentDate[1].ToString(CultureInfo.InvariantCulture) + segmentDate[2].ToString(CultureInfo.InvariantCulture) + segmentDate[3].ToString(CultureInfo.InvariantCulture);
var month = segmentDate[4].ToString(CultureInfo.InvariantCulture) + segmentDate[5].ToString(CultureInfo.InvariantCulture);
var day = segmentDate[6].ToString(CultureInfo.InvariantCulture) + segmentDate[7].ToString(CultureInfo.InvariantCulture);
//s[8] == "T";
var hours = segmentDate[9].ToString(CultureInfo.InvariantCulture) + segmentDate[10].ToString(CultureInfo.InvariantCulture);
var minutes = segmentDate[11].ToString(CultureInfo.InvariantCulture) + segmentDate[12].ToString(CultureInfo.InvariantCulture);
var seconds = segmentDate[13].ToString(CultureInfo.InvariantCulture) + segmentDate[14].ToString(CultureInfo.InvariantCulture);
string milliseconds = null;
if (segmentDate.Contains("."))
milliseconds = segmentDate.Split('.')[1].Split('-')[0];
if (milliseconds != null && milliseconds.Contains((" ")))
{
milliseconds = milliseconds.Split(' ')[0];
}
var offset = Convert.ToInt32(segmentDate.Split('-')[1].Split('/')[0]);
var a = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month),
Convert.ToInt32(day), Convert.ToInt32(hours), Convert.ToInt32(minutes),
Convert.ToInt32(seconds), Convert.ToInt32((milliseconds ?? "0"))).AddHours(offset);
But that is a bad idea - and I cannot believe that this format isnt specified somewhere (that I have been able to find).
Any help is appreciated.
Thank you!
Update
4 digit year
2 digit month
2 digit day
T - denotes start of the time portion
2 digit hour
2 digit minute
2 digit second
. - denotes start of MS
3 digit ms
TZ offset (-04)
/0 I believe is offset minutes
Update2
So I have been playing with TryParseExact and ParseExact - and cannot come up with a format string that will pull this into a DateTime/DateTimeOffset type.
I also consulted with the supplier of this value and they also have a manual process to parse it out, like I posted already.
I cannot accept that this is the only way to achieve the desired result, and as such, will continue to play with it.
But if anyone else has suggestions, they are welcome here.
Here's the closest I've gotten:
string s = "20141013T155544.673-04/0";
var dt = DateTime.ParseExact(s,"yyyyMMddTHHmmss.fffzz/0",CultureInfo.InvariantCulture);
If the /0 represents minutes (and can be 0 or 30 then you could do a little manipulation to convert that to a "standard" time zone indicator:
string s = "20141013T155544.673-04/30";
string s2 = s.Replace("/0",":00").Replace("/30",":30");
var dt = DateTime.ParseExact(s2,"yyyyMMddTHHmmss.fffzzz",CultureInfo.InvariantCulture);
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();
}
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...
}