how to avoid the changing the date in vb.net - vb.net

I would like to ask about how to code datetime in CONSOLE vb.net. I already got the format but my problem is after I inputted another data today to the database.
In this image,my data retrieval was error. The ID (1,2,3,4,5,6)should be jan 2. Unfortunately, the output was today after Ive put new data to the database. I was confused on how to code to avoid changing the date.
this is my code:
Dim datetoday As DateTime = DateTime.Now
Dim dateyesterday As DateTime = DateTime.Today
Dim format As String = "yyyy d MMM"
Sub Main()
s = New Sessions
ds = s.GetSession("select CLIENTID, SESSIONCOST from SESSIONS ORDER BY CLIENTID ASC")
Dim startVal = 0
Dim endVal = ds.Tables(0).Rows.Count
For var = startVal To endVal - 1
Console.WriteLine(ds.Tables(0).Rows(var)("CLIENTID").ToString() + " " + ds.Tables(0).Rows(var)("SESSIONCOST").ToString() + " " + datetoday.ToString(format)) 'code for display id and name
Next
Im hoping for you feedback. A sample code would be enough to understand. Thank you

Having the code in your original post is much better - but have you actually read what you've written?
Dim datetoday As DateTime = DateTime.Now
Dim dateyesterday As DateTime = DateTime.Today
These two are going to be pretty much the same thing. If you want yesterday, you would need to subtract a day from Now
Console.WriteLine(ds.Tables(0).Rows(var)("CLIENTID").ToString() + " " + ds.Tables(0).Rows(var)("SESSIONCOST").ToString() + " " + datetoday.ToString(format)) 'code for display id and name
Also - it doesn't appear that you are retrieving (or even storing?) the date in your database. If you are simply printing out the result of DateTime.Now then the date printed next to each row will always be the current date, and not necessarily when the object was created.

Try to use UTC dates (DateTime.UtcNow) in both your app and in your datastore. Only format it with the timezone adjusted date when displaying to a user.

Related

find files then parse the results before displaying the results

I'm working on an app for our customer service division. The user will enter a print number, and a mfg date. the app will then do a get files returning results of all files found with that drawing number (multiple revisions). the files are named in this format drawingnumber_rev_pages_6-digit date.pdf.
Once I have the list of that drawing number, I then take a right(string) of 10 characters to strip the 6-digit date off, and do a Date.ParseExact to compare to the user input mfg date. I was grabbing anything prior to that date, and showing them in a listbox. the criteria has now changed, and they want me to only show the file that would pertain to that build date. The problem is, I need the first rev prior to that date. and I don't fully understand the (function) portion of my getfiles statement. So I don't know what to search for to even lookup google results. as I search for getfiles, function isn't mentioned, if I look up orderby... function isn't mentioned, is it linq I need to search under? how would you propose I approach this?
original version example
new version, I can filter result and find everything before date ... but what I want is the highest revision before the mfg. date. return a single result.
current version
thank you all- here's my sample code.
Try
Dim results = Directory.GetFiles(fp, f).
OrderByDescending(Function(x) New FileInfo(x).FullName)
For Each result In results
Dim dp As String = ""
Dim d As Date
dp = Strings.Right(result, 10)
dp = Strings.Left(dp, 6)
d = Date.ParseExact(dp, "MMddyy", New Globalization.CultureInfo("en-us"))
Debug.Print(dp)
Debug.Print(d)
Dim udt As String = ""
Dim ud As Date 'user date
udt = Trim(Replace(txtMfgDate.Text, "/", ""))
If udt.ToString.Length = 0 Then lstFound.Items.Add(result)
ud = Date.ParseExact(udt, "MMddyy", New Globalization.CultureInfo("en-us"))
If d.Date <= ud.Date Then
lstFound.Items.Add(result)
End If
Debug.Print(d)
Debug.Print(ud)
If result <> Nothing Then
End If
Next
Catch x As Exception
MessageBox.Show("Error finding file: " & f)
End Try
LINQ can do everything you need with the right conditions. I also tried to clean up some of the code in other ways. I switched the LINQ expression to query comprehension to so I could use Let.
Try
Dim enusCulture = New Globalization.CultureInfo("en-us") ' consider CultureInfo.CurrentCulture instead?
Dim udt As String = Trim(Replace(txtMfgDate.Text, "/", ""))
Dim ud As Date
If udt.Length > 0 Then ud = Date.ParseExact(udt, "MMddyy", enusCulture) ' user mfg date
' 0071911_a_1_072115.pdf
Dim results = From filename In Directory.GetFiles(fp, f)
Let filedate = Date.ParseExact(filename.Substring(filename.Length - 10, 6), "MMddyy", enusCulture)
Where udt.Length = 0 OrElse filedate.Date < ud.Date
Order By filedate Descending
If udt.Length> 0 Then
results = results.Take(1)
End If
lstFound.Items.AddRange(results)
Catch x As Exception
MessageBox.Show("Error finding file: " & f)
End Try
The Function(x) syntax is a lambda expression, and it is part of LINQ method syntax for the OrderByDescending function, if you want to research that.

Strange Date Parsing Results

I am trying to make a small helper app to assist in reading SCCM logs. Parsing the dates has been pretty straightforward until I get to the timezone offset. It is usually in the form of "+???". literal example: "11-01-2016 11:44:25.630+480"
DateTime.parse() handles this well most of the time. But occasionally I run into a time stamp that throws an exception. I cannot figure out why. This is where I need help. See example code below:
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = "11-07-2016 16:43:51.541+600"
Dim dateStr_B As String = "11-01-2016 11:44:25.630+480"
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
IF run it would seem dateStr_B is an invalid time stamp? Why is this? I've tried to figure out how to handle the +480 using the 'zzz' using .ParseExact() format as shown here Date Formatting MSDN
Am I missing something with the timezone offset? I've searched high and low but these SCCM logs seem to use a non standard way of representing the offset. Any insight would be greatly appreciated
The problem is that +480 is indeed an invalid offset. The format of the offset from UTC (as produced when using the "zzz" Custom Format Specifier) is hours and minutes. +600 is 6 hours and 0 minutes ahead of UTC, which is valid. +480 would be 4 hours and 80 minutes ahead of UTC, which is invalid as the number of minutes can't be more than 59.
If you have some external source of date and time strings that uses an offset that is simply a number of minutes (i.e. +600 means 10 hours and +480 means 8 hours), you will need to adjust the offset before using DateTime.Parse or DateTime.ParseExact.
[Edit]
The following function takes a timestamp with a positive or negative offset (of any number of digits) in minutes, and returns a DateTime. It throws an ArgumentException if the timestamp is not in a valid format.
Public Function DateTimeFromSCCM(ByVal ts As String) As DateTime
Dim pos As Integer = ts.LastIndexOfAny({"+"c, "-"c})
If pos < 0 Then Throw New ArgumentException("Timestamp must contain a timezone offset", "ts")
Dim offset As Integer
If Not Integer.TryParse(ts.Substring(pos + 1), offset) Then
Throw New ArgumentException("Timezone offset is not numeric", "ts")
End If
Dim hours As Integer = offset \ 60
Dim minutes As Integer = offset Mod 60
Dim timestamp As String = ts.Substring(0, pos + 1) & hours.ToString & minutes.ToString("00")
Dim result As DateTime
If Not DateTime.TryParse(timestamp, result) Then
Throw New ArgumentException("Invalid timestamp", "ts")
End If
Return result
End Function
Thank you for the insight. I had a feeling I would need to handle this manually. I just wanted to make sure I wasn't missing something simple in the process. My knowledge of the date and time formatting is a bit lacking.
As such, I have altered my code so that it handles the offset. Granted I will have to add some more input validation in the final product.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = correctOffset("11-07-2016 16:43:51.541+600")
Dim dateStr_B As String = correctOffset("11-07-2016 16:43:51.541+480")
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
End Sub
Public Function correctOffset(ByVal ts As String)
Dim offset As Integer = CInt(ts.Substring(ts.Length - 3))
Dim offHour As Integer = offset / 60
Dim offMin As Integer = offset - (offHour * 60)
Dim strhour As String = Nothing
Dim strmin As String = Nothing
If offHour <= 9 Then
strhour = "0" & CStr(offHour)
Else
strhour = CStr(offHour)
End If
If offMin <= 9 Then
strmin = "0" & CStr(offMin)
Else
strmin = CStr(offMin)
End If
Return ts.Substring(0, ts.Length - 3) & strhour & ":" & strmin
End Function

Something is amiss in my timespan code

My code is as follows:
Private Sub tbRcvrDepartTime_textchanged(sender As Object, e As EventArgs) Handles tbRcvrDepartTime.TextChanged
'Converts the 90 Receiver Arrival & Departures Date & Times to a string for comparison
Dim raTime As String = tbRcvrArriveTime.Text 'Takes the Time only String and converts to string
Dim raDate As String = dpRcvrArriveDate.Text 'Takes the DateTimePicker and converts date to string
Dim raDateString = String.Concat(raDate, " ", raTime) 'Puts together the Date & Time into one continuous string
'Dim raDateFormat As String = "MM-dd-yyyy HH:mm" 'Sets the String to Date style Format
Dim raResultDate As Date = CDate(raDateString) 'Finalizes the String for use in below comparison
Dim rdTime As String = tbRcvrDepartTime.Text 'Takes the Time only String and converts to string
Dim rdDate As String = dpRcvrDepartDate.Text 'Takes the DateTimePicker and converts date to string
Dim rdDateString = String.Concat(rdDate, " ", rdTime) 'Puts together the Date & Time into one continuous string
'Dim rdDateFormat As String = "MM-dd-yyyy HH:mm" 'Sets the String to Date Format
Dim rdResultDate As Date = CDate(rdDateString) 'Finalizes the String for use in below comparison
'Checks to see if 2 or more hours have elapsed since Receiver Arrival/Departure Date & Time
Dim elapsedR As TimeSpan = rdResultDate.Subtract(raResultDate)
tbRcvrDepartTime.BackColor = If(elapsedR.TotalMinutes > 120, Color.LightPink, Color.White)
End Sub
Both raTime & rdTime are separate textboxes.
Both raDate & rdDate are datetimepickers.
When I run the code "live" initially the first record I look at is displayed correctly. Once I move to another record, this goes out the window... I get random results where it will not change the backcolor to the proper color if >120 minutes has elapsed. Other times it changes the backcolor when there is <120 minutes elapsed. Sometimes no change in backcolor when it should or it will change color when it should not. I attempted to originally do this using TotalHours but met with the same results. It is random and is not consistent. I have worked on this for 2 days now with no difference in results. My thinking is there needs to be a way to "refresh" the rdResultDate & raResultDate info when each new record is loaded but I am unable to do that with my code knowledge.
The code must be able to take into account if a new date is present - ie raDate: 11/01/2016 and raTime: 23:46 and
rdDate: 11/02/2016 and rdTime: 03:00 - this would exceed 2 hours (or 120 minutes) and should read "True" and change the backcolor as it is over 2 hours (or 120 minutes).
However if the following were true:
raDate: 11/01/2016 and raTime: 23:46 and
rdDate: 11/02/2016 and rdTime: 01:00 this would not exceed 2 hours (or 120 minutes) and should read "False" and would not change the backcolor.
All of this code:
Dim Detention90 As String
Try
If elapsedR.TotalMinutes > 120 Then
Detention90 = "True"
Else
Detention90 = "False"
End If
Select Case Detention90.ToString
Case = "True" : tbRcvrDepartTime.BackColor = Color.LightPink
Case Else : tbRcvrDepartTime.BackColor = Color.White
End Select
Catch ex As Exception
'If a problem occurs, show Error message box
MessageBox.Show("Receiver Arrive Time & Depart Time Elapsed error" & vbCrLf & "Lines 1424-1434")
End Try
condenses down to just this:
Dim elapsedR As TimeSpan = rdResultDate.Subtract(raResultDate)
tbRcvrDepartTime.BackColor = If(elapsedR.TotalMinutes > 120, Color.LightPink, Color.White)
Not sure if it will directly address your issue, but it was a bit too much for a comment and I've found compacting code in this way is often extremely beneficial for tracking down difficult bugs.
But in this case, I suspect the main issue is parsing the datetime values... that you're not always parsing the DateTime value you expect from a given input string. Specifically, you have format string variables raDateFormat and rdDateFormat, but then call Date.Parse() such that these format variables are never used, and you are left at the mercy of whatever the default date format is for your thread, process, or system. If you're on a system that uses a d/m/y order as in the UK instead of the US-style m/d/y, you'll end up with some strange results. You probably want DateTime.ParseExact() instead.

Subtracting days from date

I'm struggling in vein to work out how to remove 5 days from today's date...
I have the following simple code that searches compares the result of a text file array search and then compares them to today's date. If the date within the text file is older than today then it deletes, if not it doesn't.
What i want though is to say if the date in the text file is 5 days or older then delete.
This is being used in the English date format.
Sub KillSuccess()
Dim enUK As New CultureInfo("en-GB")
Dim killdate As String = DateTime.Now.ToString("d", enUK)
For Me.lo = 0 To UBound(textcis)
If textcis(lo).oDte < killdate Then
File.Delete(textcis(lo).oPath & ".txt")
End If
Next
End Sub
Thanks
You can use the AddDays method; in code that would be something like this:
Dim today = DateTime.Now
Dim answer = today.AddDays(-5)
msdn.microsoft.com/en-us/library/system.datetime.adddays.aspx
Which would make your code
Sub KillSuccess()
Dim killdate = DateTime.Now.AddDays(-5)
For Me.lo = 0 To UBound(textcis)
If textcis(lo).oDte < killdate Then
File.Delete(textcis(lo).oPath & ".txt")
End If
Next
End Sub

How can I format my "Date.Today" to go from MM/dd/yyyy to dd/MM/yyyy in VB.Net?

Basically I am having a problem fixing my "Date" and how it saves in SQL. It works now, it inserts into the table etc but not in the format I actually want it to insert like. It inserts as MM/dd/yyyy (the American Way as far as I know) but I need to be placed in the format that we use here in the UK, so yes it needs to display as dd/MM/yyyy (03/05/2014).
Is it actually possible to convert it for my different time zone & if so, how is it done? (And by done I mean guide me otherwise I won't learn.)
Here is my code on how it stands as of including my insert into the actual SQL Database.
Protected Sub OkBtn_Click(sender As Object, e As System.EventArgs) Handles OkBtn.Click
Try
' Dim DayNo As Integer = 0
' Dim DateNo As Integer = 0
' Dim StartingDay As Integer = 0
Dim ThisDay As Date = Date.Today
' Dim Week As Integer = 1
' StartingDay = ThisDay.AddDays(-(ThisDay.Day - 1)).DayOfWeek
' DayNo = ThisDay.DayOfWeek
' DateNo = ThisDay.Day
' Week = Fix(DateNo / 7)
' If DateNo Mod 7 > 0 Then
'Week += 1
' End If
' If StartingDay > DayNo Then
'Week += 1
' End If
'Dim ThisWeek As String
' ThisWeek = Week
Dim ThisUser As String
ThisUser = Request.QueryString("")
If ThisUser = "" Then
ThisUser = "Chris Heywood"
End If
connection.Open()
command = New SqlCommand("Insert Into FireTest([Date],[Type],[Comments],[Completed By]) Values(#Date,#Type,#Comments,#CompletedBy)", connection)
command.Parameters.AddWithValue("#Date", ThisDay.ToString)
command.Parameters.AddWithValue("#Type", DropDownList1.SelectedValue)
command.Parameters.AddWithValue("#Comments", TextBox2.Text)
command.Parameters.AddWithValue("#CompletedBy", ThisUser)
'command.Parameters.AddWithValue("#Week", ThisWeek)
command.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Please make sure all fields are filled in!")
End Try
connection.Close()
Response.Redirect("~/Production/Navigator.aspx")
End Sub
EDIT: I have edited the way it inserts & that works but still , it doesn't appear as dd/MM/yyyy.
Since your database column is a date type, remove the .ToString call when adding the parameter:
command.Parameters.AddWithValue("#Date", ThisDay)
don't save date time as string in your database, if you have date time data type in Date column
command.Parameters.AddWithValue("#Date", ThisDay)
you don't need to call tostring
but in this case i would not even use parameter. i will let db to insert the date
Insert Into FireTest([Date],[Type],[Comments],[Completed By]) Values(GETDATE(),#Type,#Comments,#CompletedBy)
It may be possible to try Date.Today.ToShortDateString .
The other method that i use it Date.Today.ToString("dd/MM/yyyy")
Try them and then get back to me.
EDIT:
Try this :
Dim culture As New CultureInfo("fr-FR")
Date.Today.ToString("dd/MM/yyyy", culture)
When using AddWithValue the type of the added value should reflect the column type in DB. Just change your code to this:
command.Parameters.AddWithValue("#Date", Date.Today)