Manipulating Date in Excel code - datetime

A column in an excel worksheet holds the month in this format:
Oct_2010
What I want to do is, get the last date of that month. What I figured I would do is, read the month in the cell, get the first day of the next month and then subtract one day, so I get the last date of the previous month.
But, how can I get Excel (VBA code) to read Oct_2010 as Oct 2010?

In VBA
Function LastDayFromString(sDate As String) As Date
Dim dtTemp As Date
If Not sDate Like "???[_]####" Then Err.Raise 9999, , "Invalid date string format"
dtTemp = DateValue(Replace(sDate, "_", "/"))
LastDayFromString = DateSerial(Year(dtTemp), Month(dtTemp) + 1, 0)
End Function
Used like
?lastdayfromstring("Oct_2010")
10/31/2010

How about:
=DATE(YEAR(REPLACE(A1,4,1,"/")),MONTH(REPLACE(A1,4,1,"/")),0)
Where A1=Oct_2010

Related

Add Days to Date with 'YYYYMMDD' format

In VB6, I am trying to add days to a date which is in the format 'YYYYMMDD'. I can add days like this:
Pull_Date = Need_Date + Val(txtLeadTime.Text)
which works, until the resulting days is greater than the number of days in the month. I tried using DateAdd, but it doesn't accept the YYYYMMDD format - neither does CDate.
You need to convert your date string to a date so you can use the DateAdd function:
Dim Need_Date As String
Dim Pull_Date As Date
Dim tmpDate As Date
Need_Date = "20141113"
tmpDate = CDate(Mid$(Need_Date, 5, 2) & "/" & Right$(Need_Date, 2) & "/" & Left$(Need_Date, 4))
Pull_Date = DateAdd("d", Val(txtLeadTime.Text), tmpDate)
MsgBox Format$(Pull_Date, "yyyymmdd") '// if LeadTime is 25 days, displays 20141208
Please note, parsing your Need_Date by character position can blow up if it's not formatted exactly as expected.
After digging deeper into this old code, I found that a conversion function was already created:
Public Function Date_Format_YYYYMMDD(ByVal sDate As String) As String
If IsDate(sDate) Then
sDate = Format(sDate, "YYYYMMDD")
End If
Date_Format_YYYYMMDD = sDate
End Function
With this function, it's really easy:
Pull_Date = Date_Format_YYYYMMDD(Need_Date) + Val(txtLeadTime.Text)
The only thing I don't understand is why
Pull_Date = Format(Need_Date, "YYYYMMDD") + Val(txtLeadTime.Text)
doesn't work. Seems like it's doing the same thing as the function.

Get the values from a string

I need help with a quick question I a string "07/10/2014" how can I get first the year "2014",second the month "10" ,third the day- "07" with out "/" only the values in VB.NET
Please show me the full way how to do it.
First declare it like this Dim x as Date = "07/10/2014". And to get the individual values use x.Day, x.Month and x.Year
Use the DateTime.Parse() method then use the return DateTime structure to extract the Month, Day, Year properties (similar to DJK's answer above).
If the thread's current culture is set to one that understands "mm/dd/yyyy" format, then the code can be as simple as:
Dim dt As DateTime = DateTime.Parse("07/15/2014")
MessageBox.Show(String.Format("Month: {0}; Day: {1}; Year: {2}", dt.Month, dt.Day, dt.Year))
Have a look at this.
Dim MyDate As Date
MyDate = "07/10/2014"
MsgBox(Format(MyDate, "dd")) ' dd gives you day number
MsgBox(Format(MyDate, "MM")) ' MM gives you month number
MsgBox(Format(MyDate, "YYYY")) ' YYYY gives you year number
The full list of date fomatting string could be found here (MSDN)
UPDATE
Use following example to assign to a string variable
Dim DayOfString As String DayOfString
DayOfString = Format(MyDate, "dd")

How do I convert a string date saved in seperate variables to a date using asp.net vb? The month variable is written out in text format

The data that I have to convert is written as the separate variables "Month", "Day", and "Year".
The data I need to convert for example is:
Month is "July"
Day is "21"
Year is "2013"
Combine it and use DateTime.ParseExact with CultureInfo.InvariantCulture:
Dim dtStr = String.Format("{0} {1} {2}", month, day, year)
Dim dt = Date.ParseExact(dtStr, "MMMM dd yyyy", CultureInfo.InvariantCulture)
Also have a look at: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
If you don't know if the data is valid you should use DateTime.TryParseExact:
Dim dt As DateTime
If Date.TryParseExact(dtStr, "MMMM dd yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, dt) Then
Console.Write("Date is: " & dt.ToShortDateString())
End If
I would first put the date into a string so
Dim dateString as string = string.format({0} {1} {2}, day, month, year)
Where day, month, year reference the variables holding the date values.
Then try
Dim result as DateTime = Convert.ToDateTime(dateString)

How to convert string to datetime format classic asp

I have one variable
Dim tt="2008-10-20 10:00:00.0000000"
I want to change it into date,
Try CDATE(tt) see http://www.w3schools.com/vbscript/func_cdate.asp. I used
vbscript cdate
as keywords at Google. There were more results.
Edit: Based on the comment below (I'm sorry for mixing up), using
FormatDateTime(date,format)
Format contains following constants:
0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if
specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm
(copied from http://www.w3schools.com/vbscript/func_formatdatetime.asp)
This link, (MS CDate page), explains that:
adate = CDate(astring)
converts a string into a date object. For there, you can format it with the FormatDateTime function
str = FormatDateTime(Date)
the FormatDateTime function is "smart" -- it will format as date and time if both are present, otherwise it will format with whichever of date or time is present.
I propose a safe solution which returns the result only if the conversion is successful:
s="2008-10-20 10:00:00.0000000"
On Error Resume Next
d=CDate(Left(s,19))
On Error Goto 0
if not IsEmpty(d) then MsgBox d
Try it for a non-valid date or non-valid format. The result will be empty.
s="2008-02-31 10:00:00"
In same contexts, it is necessary to initialize the variable collecting result of CData. I recommend to initialize it as Empty. Example below shows such case - counting valid dates in a string array:
Lines = array("2008-10-20 10:00:00.0000000", "2008-10-20 10:00:00", "", "2008-02-31", "Today", "2017-02-7")
On Error Resume Next
Count=0
for each Line in Lines
d=Empty
d=CDate(Line)
if not IsEmpty(d) then Count=Count+1
next
On Error Goto 0
MsgBox "Number of valid dates is "&Count
The correct answer is 2. Without initialization we get 5 as the CDate does not do anything on error so variable keeps the value from a recent iteration in the loop.
If do not need your milliseconds, your could use the following:
<script type="text/vbscript">
s="2008-10-20 10:00:00.0000000"
arr= Split(s, ".")
d=CDate(arr(0))
document.write(d)
</script>
I believe cdate is dependent on local settings to parse the string. This is no good in many situations.
To avoid this you need to use
DateSerial()
and if needed add any time components to the result separately.
The date literal in classic asp is unreliable. If the first or second part is greater than 12, it takes that value for day, the other as month. If both parts are less than 12, the interpretation is unpredictable: sometimes american and sometimes british.
A work-around is to force the entry of dates into separate fields or use a date entry module which can set the date into british or american style.
A date literal should be treated as american and use a function to convert that into a date variable using Dateserial().
function amerdate(str)
'str 3/5/2023 form: in american format: use for calculations including date
Dim d
d = Split(str, "/")
amerdate = Dateserial(d(2), d(0), d(1))
end function
Use only american date in calculations like Dateadd() etc.
someday = "3/5/2023" '5th march, american date literal
nextday = Dateadd("d", 1, amerdate(someday))
Whenever a date display is required, convert to british date and show it.
function britdate(str)
'str: 3/5/2023 form: display in british form. not for calculations
Dim d
d= Split(str, "/")
britdate = d(1) & "/" & d(0) & "/" & d(2)
end function

Convert string to date in ASP.Net

I'm trying to convert a string into a date format
My string looks like this
Dim MyString as String = "June 2011"
And I'm trying to convert it like this
Convert.ToDateTime(MyString).ToString("MM yyyy")
But it's giving me the error
Syntax error converting datetime from
character string.
The desired output would be either 06/2011 or 01/06/2011. The value of my string will only ever have the month and year in though.
Any ideas?
A datetime object in .NET represents one single point in time. To create one from a Gregorian calendar date, you need all three parts (day, month, year), otherwise it can't represent one single point in time.
Since your business requirement is to assume that the day number is 1 if not provided, just insert that number into the string before parsing.
Dim myDate As Date = Convert.ToDateTime("1 " & MyString)
EDIT:
Sorry, forgot to mention that string manipulations like that are of course culture-dependent. You don't mention what culture you are in. "June 2011" can imply either en-GB or en-US. Since inserting the day number at the start of the string is easier than trying to insert it between the month and year, I suggest you go for something like this.
Dim myDate1 As Date = Date.Parse("1 " & myString, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.AllowWhiteSpaces)
Convert.ToDateTime() only takes the full date so try prepending 01 as the day first i.e.
Convert.ToDateTime("01 " + MyString)
DateTime.Parse(MyString).ToString("MM yyyy")
This worked for me
Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture
Dim MyString As String
Dim d As DateTime = DateTime.Now 'test start
'test all Month Year strings
For x As Integer = 1 To 12
MyString = d.ToString("MMMM yyyy") 'convert date to March 2011 then April 2011 then...
Dim dt As DateTime = DateTime.ParseExact(MyString, "MMMM yyyy", provider)
Debug.WriteLine(MyString & " " & dt.ToString)
d = d.AddMonths(1)
Next

Resources