DateTime is one month off when formatting? - oop

I ran into this, and thought my server was crazy, but after testing it in
Codepad I run into the same results. After using Datetime to try and
process my date stamp I end up one day and one month OFF my original date
after trying to format back to a string?? What madness is going on here?
Here's the code
echo $obj->attributes->timestamp; // output: Jun 25, 2013 11:43:52:875 AM
$date = New \DateTime();
$date->createFromFormat(
'M j, Y h:i:s:B A',
$obj->attributes->timestamp
);
echo $date->format('M j, Y'); // output: Jul 24, 2013

public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
It is static and returns new DateTime, but you are not using returned value but current date created by calling DateTime empty constructor.
Example from PHP docs, how to use it properly:
<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');

Related

Cucumber-java-Startdate shouldn't be todays date in Java script

I am new to this code.
While running automation script, the date is automatically picked todays date.
actually the date starts from 01/01/2022.
How to change this code?
public void validateStartDateDefaultValueNew() throws Exception{
Date date = Calendar.getInstance().getTime();
DateFormat date formatter = new SimpleDateFormat( pattern: "dd/MM/yyyy");
String today = dateformatter.format(date);
System.out.println("today is "+today);
System.out.println("formatted today is "+date formatter.parse(today))
String [] actual1 = searchStartDateInput.getAttribute("value").split(regor " ");
String actual actuall[0]; =
System.out.println("today actual app is [+actual);
Assert.assertEquals(today, actual);
In your code, you mentioned -
'Date date = Calendar.getInstance().getTime();'.
This line of code takes today's date and current time.
If you want the start date to be '01/01/2022', then hard-code it in your code.

Powershell $cmd.ExecuteNonQuery() changes DATETIME to NVARCHAR

Caveat: I am new to PowerShell...
I am trying to automate a load process for 48 tables. The table names are all of the format "Vocabulary_MMddyyyy", as in "Vocabulary_12052016". I have no trouble iterating through the table names and parsing out the MMddyyyy part (the release version for the vocabulary). Powershell does not recognize the '12052016' as a proper datetime format. So, I do some parsing to build a proper date string that I convert to DateTime with the Get-Date cmdlet:
$version = ($table.Table_name -replace 'Vocabulary_', '').Trim();
$mm = $version.Substring(0,2);
$dd = $version.Substring(2,2);
$yyyy = $version.Substring(4,4);
$date = $mm + "/" + $dd +"/" + $yyyy
$startDate = Get-Date -Date $date -Format "d"
$endDate = ($startDate).AddDays(-1)
write-host 'Version: ' $version
write-host 'StartDate: ' $startDate
write-host 'EndDate: ' $endDate
This properly sets $startDate and $endDates (though despite the "d" format, I still get HH:MM:SS AM part):
Version: 12052016
StartDate: 12/5/2016 12:00:00 AM
EndDate: 12/4/2016 12:00:00 AM
This is the SQL signature of the stored procedure I want to call:
CREATE PROCEDURE [vocab].[prInsertLoadProcessID] (
#CodeQualifierID INT,
#SourceVersion VARCHAR(100),
#SourceDate DATE,
#LoadTypeID INT,
#isTestLoad BIT,
#ValidationDate DATE,
#LoadDescription VARCHAR(500),
#GlobalEffectiveDateStart DATE,
#GlobalEffectiveDateEnd DATE
)
Now, I go to build up a SQL command to execute the stored procedure ($conn2 is properly defined and open; it executes simple select statements yielding correct results):
$cmd.Connection = $conn2;
$cmd.CommandText = "vocab.prInsertLoadProcessID ";
$cmd.CommandType = [System.Data.CommandType]::StoredProcedure;
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.Connection = $conn2;
$cmd.CommandText = "vocab.prInsertLoadProcessID ";
$cmd.CommandType = [System.Data.CommandType]::StoredProcedure;
$cmd.Parameters.AddWithValue("#CodeQualifierID", 6);
$cmd.Parameters.AddWithValue("#SourceVersion", $version);
$cmd.Parameters.AddWithValue("#SourceDate", $startDate);
$cmd.Parameters.AddWithValue("#LoadTypeID", 1);
$cmd.Parameters.AddWithValue("#isTestLoad", 0);
$cmd.Parameters.AddWithValue("#ValidationDate", 'NULL');
$cmd.Parameters.AddWithValue("#LoadDescription", $LoadDescription);
$cmd.Parameters.AddWithValue("#GlobalEffectiveDateStart", $startDate);
$cmd.Parameters.AddWithValue("#GlobalEffectiveDateEnd", $endDate);
Each of the dates (#SourceDate, #GlobalEffectiveDateStart, #GlobalEffectiveDateEnd) show as DateTime when I look at the output from adding the parameters (here is one example):
CompareInfo : None
XmlSchemaCollectionDatabase :
XmlSchemaCollectionOwningSchema :
XmlSchemaCollectionName :
ForceColumnEncryption : False
**DbType : DateTime**
LocaleId : 0
**ParameterName : #GlobalEffectiveDateEnd**
Precision : 0
Scale : 0
**SqlDbType : DateTime**
SqlValue : 12/6/2015 12:00:00 AM
UdtTypeName :
TypeName :
Value : 12/6/2015 12:00:00 AM
Direction : Input
IsNullable : False
Offset : 0
Size : 0
SourceColumn :
SourceColumnNullMapping : False
SourceVersion : Current
When I run $cmd.ExecuteNonQuery() I get:
Exception calling "ExecuteNonQuery" with "0" argument(s): "Error converting data
type nvarchar to date." this is a Category: MethodInvocationException and a FullyQualifiedErroID: SQLException.
So, after reading for hours and trying everything I can think of I am stuck. My variables appear to be typed as DATETIME, but ExecuteNonQuery() seems to read treat them as NVARCHAR.
What am I missing? I can certainly rewrite the stored procedure to take strings instead of dates and let SQL do the conversion, but it really seems I should be able to pass dates from Powershell to SQL.
There must be a solution to this. What is causing the $cmd.ExecuteNonQuery() to change the datatype of my inputs? Or, am I setting up the $cmd.Parameters incorrectly?
Kind thanks for any help.

hive equivalent for TD_WEEK_OF_CALENDAR

I am trying to implement a query already written for Teradata in Hive and was using weekofyear() until now as a replacement of TD_WEEK_OF_CALENDAR method which returns an INTEGER value representing the number of full weeks since and including the week of 01/01/1900, where the first partial week is 0.
I couldn't find any other predefined UDF in Hive related to this method. Even for writing a custom UDF in Java, I was not able to get the exact logic of TD_WEEK_OF_CALENDAR.
Can someone please help on this?
This can be achieved using the Joda time functions. But Hive doesn't support Joda time Jars and you need to explicitly add the joda-time jars to your hive lib folder.
The function TD_WEEK_OF_CALENDAR treats Sunday as first day of week and Saturday as last whereas the joda-time function getDayOfWeek() treats Sunday as last day of the week giving its number as 7 which pulls Sunday into the same week.
This below code would to the needful
public Text evaluate(Text input) {
if(null != input){
String date = input.toString();
StringTokenizer st = new StringTokenizer(date, "-");
int year = Integer.parseInt(st.nextToken());
int month = Integer.parseInt(st.nextToken());
int day = Integer.parseInt(st.nextToken());
DateTime dateTime1 = new DateTime(1900, 1, 1, 0, 0, 0, 0);
DateTime dateTime2 = new DateTime(year, month, day, 0, 0, 0, 0);
int weeksDiff = dateTime2.getDayOfWeek() == 7 ? Weeks.weeksBetween(
dateTime1, dateTime2).getWeeks() + 1 : Weeks.weeksBetween(
dateTime1, dateTime2).getWeeks();
String weeks = weeksDiff + "";
return new Text(weeks);
} else {
return null;
}

axis2 xsd:date format issue

I have WSDL as follows:
< xsd:simpleType name="USER_ACT_STRDT_TypeDef">
< xsd:annotation>
< xsd:documentation>USER_ACT_STRDT is a date.< /xsd:documentation>
< /xsd:annotation>
< xsd:restriction base="xsd:date">
< xsd:pattern value="(\d{4}-\d{2}-\d{2})"/>
< /xsd:restriction>
< /xsd:simpleType>
When I generate the STUB (using Axis2 1.5.3), the generated stub (ADB Data Binding) has the following source code :
public void setUSER_ACT_STRDT_TypeDef(Date param) {
if (ConverterUtil.convertToString(param).matches("\d{4}-\d{2}-\d{2}")) {
this.localUSER_ACT_STRDT_TypeDef=param; } else { throw new java.lang.RuntimeException();
} }
This method always throws RuntimeException because the ConverterUtil.convertToString() method returns a String in a different format than "yyyy-mm-dd". It returns the date by appending +5.30 as 2011-03-21+05:30.
I tried passing the date in different formats but same result for all.
Can any one suggest how to resolve this issue.
This code:
if (ConverterUtil.convertToString(param).matches("\\d{4}-\\d{2}-\\d{2}"))
will work only with one of date representations available. In WSDL date specification you will find that 2011-03-21+05:30 is also correct date representation, it simply include time zone as +5 hours and 30 minutes offset to UTC.
Axis2 by default generate dates with timezone but should be able to operate on other date formats.
To check if string starts with YYYY-MM-DD date you can use such code:
if (! sd.matches("\\d{4}-\\d{2}-\\d{2}.*"))
throw new ParseException("Something is terribly wrong with date: " + sd, 0);
else
{
sd = sd.substring(0, 10);
System.out.println("ok: '" + sd + "'");
}
PS Do you escape \d as \\d?
PPS Why do you throw RuntimeException? There are much "better" exceptions like ParseException (used by JDK date parsing methods) or IllegalArgumentException (used by joda time library)

How can i parse from SQL datetime to JSON and finally to java.util.Date?

i have a remote sql satabase, and i connect him by php with JSON.
I can get string and int data OK, but now i have a problem.... i have a datetime field on my SQL database, and i dont know how to get it with JSON into java.util.Date
this is the code i tryed, but it fails getting the Date correctly, it gives me an exception (java.lang.ClassCastException: java.lang.String)
code:
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
positions.add(new Position(json_data.getString("latitude"), json_data.getString("longitude"), (Date)json_data.get("timestamp")));
}
You will have to fetch the string sent in the JSON data and parse that string with something like SimpleDateFormat.
In my projects I have used two different solutions.
Storing the Date not as Date but as long(milisecs since 1.1.1980). In Java you can get this with date.getTime(). There should also a methode in PHP. The get the Date Object in Java just pass the long value to the constructor(date= new Date(long_value)).
With this Method you may have problems when dates comes from different time zones.
Write the Date as a formatted Date String in the JSON. How you encode the Date is up to you. A short sample give below. see[1] for further infos.
To get the Date you need a SimpleDateFormater.
DateFormat df = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
try
{
Date today = df.parse("2001.07.04 AD at 12:08:56 PDT");
System.out.println("Today = " + df.format(today));
}
catch (ParseException e)
{
e.printStackTrace();
}
[1]http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html