Data Conversion with DatePart in an MS access select query - select

I am trying to use DatePart() within a MS Access select query to extract a month and year-- as a number-- from a date which is initially in a string form of
"YYYY-MM-DD HH:NN:SS.0000000"
The initial code written by someone else says:
DatePart("m", date)
DatePart("yyyy", date)
But this was causing a "Data Type, Mismatch in Criteria" error when the query ran, so I attempted to use Cdate() to convert the string to a date type.
DatePart("m", Cdate(date))
DatePart("yyyy", Cdate(date))
However this did not solve the problem. I am wondering if my initial date string is not in a form that Cdate() can convert, or if there is an easier way to extract a partial, numerical date from a date string such as mine.
I am prepared to elaborate much further on the situation in case this question is incomplete, but I did not wish get ahead of myself.

Those extra zeros would be a problem, to strip them, you could say
CDate(Mid(sdate, 1, InStr(sdate, ".") - 1))
Then
DatePart("m", CDate(Mid(sdate, 1, InStr(sdate, ".") - 1)))
However, you may find it more convenient to just refer to the appropriate part of the string:
aYr = Left(sdate,4)
aMnth = Mid(sdate,6,2)

You were right that the fractional seconds prevent CDate from accepting your string. And you could strip away the fractional seconds. But since you ultimately want the year and month, you can ignore all of the time components and just use the date part.
See whether this Immediate window session offers anything useful.
MyString = Format(Now(), "yyyy-mm-dd hh:nn:ss") & ".0000000"
? MyString
2013-02-14 23:38:09.0000000
' if date format is always yyyy-mm-dd,
' give CDate the first 10 characters
? CDate(Left(MyString, 10))
2/14/2013
' year
? DatePart("yyyy", CDate(Left(MyString, 10)))
2013
' or
? Year(Left(MyString, 10))
2013
' month
? DatePart("m", CDate(Left(MyString, 10)))
2
' or
? Month(CDate(Left(MyString, 10)))
2
' if date format can vary slightly, eg yyyy-m-d,
' give CDate everything before the first space
? CDate(Left(MyString, InStr(MyString, Chr(32)) -1))
2/14/2013
? Year(CDate(Left(MyString, InStr(MyString, Chr(32)) -1)))
2013
? Month(CDate(Left(MyString, InStr(MyString, Chr(32)) -1)))
2
You didn't mention what you will do with the year and date numbers after you get them. If you intend to join them together as a string, you could use Format().
? Format(Left(MyString, 10), "yyyymm")
201302

Related

SSRS exact month difference

This may have been asked before but I've not been able to find it having searched! In Oracle SQL there's a function called MONTHS_BETWEEN which returns a fractional value if the two dates you are comparing are not both the first day of the month for example. I need to do something similar in SSRS report builder, I've tried using DateDiff("m",Date1,Date2) however this always returns an integer and I think from what I can tell it just compares the two months from the dates, so when I compare 30/09/20 and 01/04/21 I get 7 months when actually it is much closer to 6.
Is there a function or a fix that can be used in SSRS to get that more accurate value?
Thank you!
For example I would like to get the following result:
Difference between 30/09/20 and 01/04/21 = 6.1
Difference between 01/08/20 and 30/09/20 = 1.9
It doesn't have to super accurate as I will be rounding to the nearest integer but I'm looking for something that will recognise that in the second example nearly 2 months have been covered and in the first example it's only just over 6 months.
If you only need an approximation then you could just calculate the number of days difference and divide by 30.
using the following expression...
=DATEDIFF("d", Fields!startDate.Value, Fields!endDate.Value)/30
I put a few more examples into a table and got the following results.
The following code mimics oracle definition of months_between
Public Function MonthsBetween( d1 As Date, d2 As Date) As Decimal
Dim df As Decimal
df = DateDiff("m", d1, d2)
If Day(d1) <> Date.DaysInMonth(Year(d1), Month(d1)) Or Day(d2) <> Date.DaysInMonth(Year(d2), Month(d2)) Then
df = df + Cdec((Day(d2)-Day(d1))/31)
End If
Return df
End Function
Integer result when both dates are last day of month
Negative result when date1 > date2
Decimal part based on 31 days month
For your expression use something like
=Code.MonthsBetween(Fields!date1.Value , Fields!date2.Value)
UPDATE
The following expression works in the same manner
= Cdec(
DateDiff("m", Fields!date1.Value, Fields!date2.Value)
+
Iif (
Day(Fields!date1.Value) <> Date.DaysInMonth(Year(Fields!date1.Value), Month(Fields!date1.Value)) Or
Day(Fields!date2.Value) <> Date.DaysInMonth(Year(Fields!date2.Value), Month(Fields!date2.Value)) ,
Cdec( (Day(Fields!date2.Value) - Day(Fields!date1.Value))/31),
0.0
)
)

Convert year and month variables to timestamp in Postgresql

I have to variables: year and month, both of type integer.
E.g:
year = 2016
month = 1
I want to, in my select statement, return a timestamp given those two variables.
I've had a look at the documentation, specifically to_timestamp and to_date, but all the examples I've come across show a string being converted into a timestamp.
I do not really want to convert my year and month into a string, such as:
to_timestamp(to_char(int,year) + ' ' + to_char(int, month),YYYY/MM/DD HH24:MI:SS)
So, how can I (if it is possible) convert my year and month into a timestamp?
If you are using Postgres 9.4 or later, you could try using make_timestamp():
make_timestamp(2016, 1, 1, 0, 0, 0.0)
This would create a timestamp for January 1, 2016 at midnight. We need to specify values for the other components, even if they end up not being relevant to your query/calculation (e.g. you only need the date).

Talend date and time combine

I combine two columns; date and time. When I pass the date and time hot coded it works fine but when I pass it through a column it throws the error:
Unparseable date: "05/05/1992"
I already tried this:
MaterialCodeCSV.xdate == null ?
TalendDate.parseDate("yyyy-MM-dd HH:mm:ss", TalendDate.getDate("yyyy-MM-dd HH:mm:ss")) :
TalendDate.parseDateLocale("yyyy/mm/dd HH:mm:ss",MaterialCodeCSV.xdate.toString() + MaterialCodeCSV.xtime.toString(),"EN");
Java code in Talend:
Date handling can be a bit tricky if using wrong data types. I assume you want to fill a field which is a Date. There are several errors with this way:
MaterialCodeCSV.xdate == null ?
TalendDate.parseDate("yyyy-MM-dd HH:mm:ss", TalendDate.getDate("yyyy-MM-dd HH:mm:ss")) :
TalendDate.parseDateLocale("yyyy/mm/dd H:mm:ss",MaterialCodeCSV.xdate.toString()+ MaterialCodeCSV.xtime.toString(),"EN");
If MaterialCodeCSV.xdate == null you create a date and parse it again instantly? That seems unneccessary complex and inefficient. Change this to TalendDate.getCurrentDate()
Then if xdate is not null, you just concat xdate and xtime, use toString() and try to parse this. Again, this seems unneccesary complex. If I just assume now and xdate and xtime are already Date fields, you could write it as this: MaterialCodeCSV.xdate + MaterialCodeCSV.xtime.
If both are String fields, you have to make sure that xdate is formatted yyyy/MM/dd and xtime is HH:mm:ss. Then you could exclude .toString()
Also, if both are String fields, you have to add an additional space: MaterialCodeCSV.xdate + ' ' + MaterialCodeCSV.xtime
Additionally, in the first case you parse with yyyy-MM-dd HH:mm:ss. In the second case you parse with yyyy/mm/dd H:mm:ss. This reads "year/minute/day". Also there is only one hour digit, not allowing anything after 9:59:59 o'clock to be parsed. Correctly you should use yyyy/MM/dd HH:mm:ss.
So to conclude it should look like this (if I assume correctly and you are using correctly formatted String fields for xdate and xtime):
MaterialCodeCSV.xdate == null ?
TalendDate.getCurrentDate() :
TalendDate.parseDateLocale("yyyy/MM/dd HH:mm:ss", MaterialCodeCSV.xdate + ' ' + MaterialCodeCSV.xtime,"EN");

MS Access : Dealing with today's date in calculated field expression

Hi I am creating a table in MS Access to store the details of children in a school.
I have a field called YearGroup which needs to calculate the school year they are in based on their date of birth and whether they have been moved up or down a year.
I.e. if the expression deems they are six years old they should be placed in year 2. If they were moved down or up a year they should be in year 1 or 3 (this is based on another field in the table called YearModifier).
The code I have at the moment is this:
Year(Now()) - IIf(Month([DOB]) > 8, Year([DOB]) + 6 + [YearModifier], Year([DOB]) + 5 + [YearModifier])
My problem is that Year(Now()) is returning as invalid expression. Lots of websites have recognised using the Now() function and also I've tried Date() but nothing seems to be accepted by Access (The version is 2010).
What is going on? How can I get today's date in a calculated field expression?
Thanks
Try creating a query with all of the fields from your table, and then add an extra field YearGroup: Year(Now()) - IIf(Month([DOB]) > 8, Year([DOB]) + 6 + [YearModifier], Year([DOB]) + 5 + [YearModifier])
It appears that Date functions can't be used in calculated columns in tables.
You could use this to get the year, which might work in field expressions:
format(date(),"yyyy")
About your function (which I have re-written very slightly)
Year( Now() )
- Year([DOB])
- IIf( Month([DOB]) > 8
, 6
, 5 )
+ [YearModifier]
however!
I don't think you want to use now(). Which year they are in depend on their age at the 1st Sept at the start of the current academic year not now! Ok now will work until 31/dec/2015, so I must assume you will not be using the function after this date!
If you are you must use 2015 not Now().
Ok?
You can calculate the age of the children with a simple function:
Public Function AgeSimple( _
ByVal datDateOfBirth As Date) _
As Integer
' Returns the difference in full years from datDateOfBirth to current date.
'
' Calculates correctly for:
' leap years
' dates of 29. February
' date/time values with embedded time values
'
' DateAdd() is used for check for month end of February as it correctly
' returns Feb. 28. when adding a count of years to dates of Feb. 29.
' when the resulting year is a common year.
' After an idea of Markus G. Fischer.
'
' 2007-06-26. Cactus Data ApS, CPH.
Dim datToday As Date
Dim intAge As Integer
Dim intYears As Integer
datToday = Date
' Find difference in calendar years.
intYears = DateDiff("yyyy", datDateOfBirth, datToday)
If intYears > 0 Then
' Decrease by 1 if current date is earlier than birthday of current year
' using DateDiff to ignore a time portion of datDateOfBirth.
intAge = intYears - Abs(DateDiff("d", datToday, DateAdd("yyyy", intYears, datDateOfBirth)) > 0)
End If
AgeSimple = intAge
End Function
Then your expression would be something like this (ignoring the modifier):
ClassYear: IIf(AgeSimple([DOB]) > 6, 2, 1)

How to write expression to convert yyyymm to mm-yyyy in ssrs?

I have a table with a YearMonth column (201302) in it.
I created YearMonth a parameter.
Now I would like to write an expression in SSRS so that every time the report runs the date and month would look like this Feb-2013.
Could you please suggest me why following expression did not work.
Thanks
=CStr(Right(MonthName(Month(Parameters!NLR_YearMonth.Value)),3))
+ "-" +
Left(Year(Parameters!NLR_YearMonth.Value),4)
Try This:
=Format(DateValue(MonthName(Right(Parameters!NLR_YearMonth.Value, 2))
+ "," +
Left(Parameters!NLR_YearMonth.Value,4)), "Y")
The expression goes as follows:
Cutting the string to get the month.
Converting the mount to MountName
Creating a comma seperator between the month and the year
Cutting the string to get the year
Converting the returns string to Date object using the DateValue function
Formatting the Date to fits your needs
The results should be:
February, 2013