I have a month key which look like this "201208".
I am reading the data from SQL and returning as a DataTable.
Then I am looping through my DataTable.
For Each dr As DataRow In dt.Rows
Dim s As String = dr.Item(0)
Next
My s would be a string looking like this "201208"
How convert this string into year, first day of the month and last day of the month?
Looking for a way to split the string into two seperate dims.
Any suggestions much appreciated.
The easiest way is to just parse the string as Date, then calculate the last day of the month.
Try the following:
Dim s = "201208"
Dim firstDay = Date.ParseExact(s, "yyyyMM", Nothing)
Dim lastDay = firstDay.AddMonths(1).AddDays(-1)
Dim year = firstDay.Year
Firstly I would use DateTime.TryParseExact Method with format "ddMMyy" to parse the string into a DateTime.
Then I would use something like
Dim startDate As New DateTime(dbDate.Year, dbDate.Month, 1)
Dim endDate As DateTime = startDate.AddMonths(1).AddDays(-1)
to get the StartDate and EndDate
This works for me:
Function FormatDate(ByVal dateKey As String) As String
Dim x As DateTime = DateTime.ParseExact(dateKey, "yyyyMM", Nothing)
FormatDate = String.Format("Year: {0}; First day of month: {1}; Last day of month: {2}", x.Year, x.AddDays(-x.Day).ToString("dddd"), x.AddMonths(1).AddDays(-x.Day).ToString("dddd"))
End Function
You can use this function as so:
Dim dateDetails As String = FormatDate("201208")
Split that string into a year and month (see Substring)
Use "1" as the first of the month -> that's your start date
Add one month, subtract one day -> that's your end date
Related
so i have this problem, i want to make specific number to become a day of month.
example: i had an output of label 5 now how to make it to become 05-12-2016 ? i just convert them into string like this
dim testing as string = ""
testing = Now.Year.ToString & Right("0" & Now.Month.ToString, 2) & Right("0" & "5" 2)
output :
2016-11-05
and if i use string, i cannot compare it with date.Now
Thanks in advance
DateTime has a constructor that takes the year, month and day of month as parameters that you can use to create an instance:
Dim dayOfMonth As String = "5"
Dim myDate = New Date(Date.Now.Year, Date.Now.Month, CInt(dayOfMonth))
You can use the ToString method to format the date however you need:
Dim format1 As String = myDate.ToString("yyyy-MM-dd")
Dim format2 As String = myDate.ToString("dd-MM-yyyy")
I'm doing the following query to check if the current month is the same as the SQL field "Start".
If Today.Month = CDate(rsData("Start")).Month Then
What I'd like to do is switch it so that it will check within a 30 day period rather than identify the current month? Any ideas on how to do this?
If Date.Today.AddDays(-30) >= CDate(rsData("Start"))
' start date not older than 30 days '
End If
or if you have a variable date:
var minBoundary = New Date(2011,1,1)
var maxBoundary = New Date(2012,1,1)
var startDate = CDate(rsData("Start"))
If startDate >= MinBoundary AndAlso startDate <= maxBoundary
' start date between two dates '
End If
I believe in this case you would want to use the AddDays method of DateTime.
Dim mydate as DateTime = CDate(rsData("Start"))
Dim checkdate as DateTime = mydate.AddDays(30)
How do I calculate the difference between two dates to display as a number in days?
I have 2 text boxes (txtHStart_Date & txtHEnd_Date) I have used an Ajax Calendar Extender to enter the dates in each of these text boxes.
I would like to get the difference between these two dates to show in a seperate text box (txtNoOfDays)
I've seen the timespan function but can seem to get this to work.
I'm not to sure how to declare the text boxes as the dates I would the calculation to be made from
Code:
Dim D1 As Date
Dim D2 As Date
Dim ts As New TimeSpan
D1 = txtHStart_Date.Text
D2 = txtHEnd_Date.Text
ts = D2 - D1
But I know this isn't right. I also don't know how to get it to display in the 3rd TextBox.
The TimeSpan is simple to use.
Dim dtStart As DateTime = DateTime.Now.AddDays(-100)
Dim dtEnd As DateTime = DateTime.Now
Dim ts As TimeSpan = dtEnd - dtStart
Console.WriteLine(ts.TotalDays)
Edit:
And going by the comment you added where you assign a text string to a date variable, you would be better off using (and handling)
DateTime.TryParse("some date string", dtStart)
TryParse returns a boolean success/fail so you can react to whether you were given good/bad data.
This is the best I know so far. StringToDate function let's you decide what date format you want to use.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
txtHStart_Date.Text = "11/20/2011"
txtHEnd_Date.Text = "11/25/2011"
Dim dtHStart_Date As DateTime = StringToDate(txtHStart_Date.Text, "MM/dd/yyyy")
Dim dtHEnd_Date As DateTime = StringToDate(txtHEnd_Date.Text, "MM/dd/yyyy")
Dim span As TimeSpan = dtHEnd_Date.Subtract(dtHStart_Date)
txtNoOfDays.Text = span.Days
End If
End Sub
Public Function StringToDate(ByVal strDate As String, ByVal pattern As String)
Dim myDTFI As New System.Globalization.DateTimeFormatInfo()
myDTFI.ShortDatePattern = pattern
Dim dtDate As DateTime
Try
dtDate = DateTime.Parse(strDate, myDTFI)
Catch ex As Exception
Return False
End Try
Return dtDate
End Function
Use the DateDiff function:
http://msdn.microsoft.com/en-us/library/b5xbyt6f(v=vs.80).aspx
"Returns a Long value specifying the number of time intervals between two Date values."
is there any ready to go solution within the microsoft framework, regarding conversion of date to day?
For example, i would like to convert this string 21/03/2010 (dd/mm/yyyy) to Sunday
Dim d = DateTime.Parse("21/03/2010").DayOfWeek()
This code will print Sunday on the console window
Dim dateToShow as DateTime = new DateTime(2010, 03,21)
Console.WriteLine(dateToShow.DayOfWeek.ToString)
This should print "Sunday".
string myDateTimeString = "21/03/2010";
DateTime dt = DateTime.ParseExact(
myDateTimeString, "dd/MM/yyyy",
new CultureInfo("en-Us", true)
, DateTimeStyles.NoCurrentDateDefault);
Console.WriteLine(dt.DayOfWeek);
I would use DateTime.TryParse() just to validate the user input.
Dim input As String = "2010/12/23"
Dim dateTime As DateTime
If DateTime.TryParse(input, dateTime) Then
Console.WriteLine(dateTime.DayOfWeek)
Else
Console.WriteLine("Invalid")
End If
I have a dropdownlist that displays time. For example 8:00AM or 8:30AM.
When I save this time to database, I want to save as todays date + time.
eg: 8:00AM as 03/30/2009 8:00:00:000. Can anybody give appropriate code to convert as shown above?
I tried
Convert.ToDateTime(ddlStartTime.SelectedItem.Text)
But there is an error stating "String was not recognized as a valid DateTime."
VB.NET answer for Portmans Solution. Too many chars for comment so included here.
Dim time As String() = Me.DropDownList1.SelectedValue.Split(New Char() {":", " "})
Dim hours As Integer = Integer.Parse(time(0))
Dim minutes As Integer = Integer.Parse(time(1))
Dim ampm As Integer = 12
If time(2).ToLower() = "am" Then
ampm = 0
End If
Dim dt As DateTime = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes)
Have a look at DateTime.TryParse and DateTime.Today. Using them should be enough to do what you want.
Untested Code.
DateTime dt;
if (DateTime.TryParse(Dropdown1.SelectedValue, out dt))
{
DateTime result = DateTime.Today.AddHours(dt.Hour).AddMinutes(dt.Minute);
}
Basically, you just need to parse the time string. It will be automatically resolved to the current date.
Dim strTime As String = "8.30am"
Dim parsedTime As DateTime
If DateTime.TryParseExact(strTime, "h.mmtt", New System.Globalization.DateTimeFormatInfo(), Globalization.DateTimeStyles.None, parsedTime) = True Then
'Parse was successful.
Else
'Handle the error.
End If
Store as the value for each drop down item the number of minutes from midnight that the time represents. Then:-
valueToStore = DateTime.Today + TimeSpan.FromMinutes(Int32.Parse(value))
By storing using the value attribute of a HTML option to store a simple representation of the value you eliminate the codes dependancy on the actual format used to simply display the set of values. If it decided that the representation of the times be changed to use different format the rest of the code will continue to work unmodified.
var time = this.DropDownList1.SelectedValue.Split(':', ' ');
var hours = Int32.Parse(time[0]);
var minutes = Int32.Parse(time[1]);
var ampm = (time[2] == "PM") ? 12 : 0;
var dt = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes);
Parse your DropDownList for Hours and Minutes, then add them to DateTime.Today.
Read the parts of the time so you have hours and minutes, then use the following code:
DateTime myDate = DateTime.Now.Date;
myDate = myDate.AddHours(hours);
myDate = myDate.AddMinutes(minutes);
Use ParseExact so that you can specify the format that you are using.
h = hours in 12-hour clock format
. = literal character
mm = minutes as two digits
tt = AM/PM designator
Dim time As DateTime = DateTime.ParseExact(dropdown.SelectedValue, "h.mmtt", CultureInfo.InvariantCulture)
The components of the DateTime value that you don't specify in the string (year, month, date, seconds, time zone, era) uses DateTime.Today as default, which is exactly what you want in this case.
This always seems to work for me. May not be the most elegant way, but I have not had any issues so far.
dTime = DateTime.Now;
string time = this.DropDownList1.SelectedValue;
DateTime FormattedDateTime = Convert.ToDateTime(dTime.Date.ToShortDateString() +
" " + time);