make the specific number to become day of month - asp.net

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")

Related

How to extract values from the '-' seperated string in VB.Net [duplicate]

This question already has answers here:
Split String in VB.net
(2 answers)
Closed 7 years ago.
I have a function in VB.Net which takes two arguments(dosage & no_days).
'dosage' have values of the 1-2-1 format.
I need to get the values as integer from the string: for example, if the string is 1-1-2, I need to get the values as 1,1,2. And sum of these three numbers need to multiply with no_days and return the result.
I need to know how can I split the string using regex "-" or any other logic for doing this.
Public Function calculateNoOfPeices(ByVal dosage As String, ByVal days As Integer) As String
Dim noOfPiece As Double = 0.0
If txt_dosage.Text.Length > 4 Then
' need logic to extract the values from the dosage
'and need to multiply with no_days
Else
'lbl_notif.Visible = False
noOfPiece = "-1"
End If
Return noOfPiece.ToString
End Function
Please help.
Using String.Split
Dim dosage As String = "1-2-1"
Dim IntValues() As String = dosage.Split("-")
Dim fValue As Double = Val(IntValues(0))
Dim sValue As Double = Val(IntValues(1))
Dim tValue As Double = Val(IntValues(2))
Using Regx
Dim pattern As String = "-"
Dim substrings() As String = Regex.Split(dosage, pattern)
Dim fValueR As Double = Val(substrings(0))
Dim sValueR As Double = Val(substrings(1))
Dim tValueR As Double = Val(substrings(2))
Or You can take the Sum using:
Dim overAllSum = dosage.Split("-").ToList().Where(Function(x) IsNumeric(x)).Sum(Function(y) Val(y))

Replace and Contains not recognizing the string

I am trying to strip the country code off the phone number and place it in the textbox txtMobile. cCode is just an empty string.
GlobalsFSiA.COUNTRY_CODES.Split(",") contains +44 and +353.
The phone number I am testing with is +353861234567
For Each code As String In GlobalsFSiA.COUNTRY_CODES.Split(",")
If objEmployee.MobilePhone.Contains(code) Then
cCode = code
End If
Next
Dim number As String = objEmployee.MobilePhone.Replace(cCode, "0")
txtMobile.Text = number
First you have to search for What is actually the split() method is used for and also difference between split() and substring():
I think Substring() is more suitable in this scenario, you can code like this for extracting country code from the given number:
Dim mobileNumber As String = "+353861234567"
Dim countryCode As String = mobileNumber.Substring(0, 3)
using this code I do get the correct result
Dim sTest As String = "+353861234567"
Dim cCode As String = ""
Dim numbers As New List(Of String)()
numbers.Add("+44")
numbers.Add("+353")
For Each code As String In numbers
If sTest.Contains(code) Then
cCode = code
End If
Next
Dim number As String = sTest.Replace(cCode, "0")
Is the cCode declared internally? Might be an option to take the value from the object before parsing it

Get a first and last day of the month from month key

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

VB.net - CDate with SQL

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 to convert to datetime

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);

Resources