Command manager procedure in MicroStrategy not converting to date - java

I am running below command manager procedure in Microstrategy but it does not convert the string into date, tried lot of options. Can someone please assist?
*********** PROCEDURE***************************************
String sQuery = "LIST ALL SUBSCRIPTIONS FOR SCHEDULE \"" + sScheduleName + "\" FOR PROJECT \"" + projectName + "\";";
ResultSet oSubs=executeCapture(sQuery);
oSubs.moveFirst();
while(!oSubs.isEof()){
String sSubsName = oSubs.getFieldValueString(DisplayPropertyEnum.GUID);
ResultSet RecList = executeCapture("LIST ALL PROPERTIES FOR SUBSCRIPTION GUID " +sSubsName+ " FOR PROJECT \"projectname\";");
RecList.moveFirst();
while(!RecList.isEof()){
ResultSet oResultSetSubProps = (ResultSet)RecList.getResultCell(SUBSCRIPTION_RESULT_SET).getValue();
oResultSetSubProps.moveFirst();
while(!oResultSetSubProps.isEof())
{
String d1 = oResultSetSubProps.getFieldValueString(DisplayPropertyEnum.EXPIRATIONDATE);
// the below few lines in red return nothing, its unable to convert to Date as it is unable to recognize the Expiration date in the String format.
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("M/dd/yyyy");
String dateInString = d1;
Date date = formatter.parse(dateInString);
printOut(formatter.format(date));
oResultSetSubProps.moveNext();
}
RecList.moveNext();
}
oSubs.moveNext();
}

This worked for me. The string was neither empty, nor null and no even blank but it would still not parse it so i had to use the length of the string.
java.text.DateFormat formatter = new java.text.SimpleDateFormat("M/d/yyyy",Locale.US);
String dateInString = d1;
if(d1.trim().length()>0)
{
Date date = formatter.parse(dateInString);
if(todaydate.compareTo(date)>0)
{
printOut(name+";"+formatter.format(date));
}
}

if(d1.contains("/"))
{
Date EDate=new Date(d1);
Date today= new Date();
if(d1.compareTo(today)<0)
{
printOut("Expired");
}
}
else
{
printOut("Active");
}
//blank or null values can be handled in Else condition instead.. Hope it helps..

Related

Avoiding a particular check for YYYY-MM--dd format in date

I have below method in which different date patterns have been handled
below is the method in which different date formats have been handled now
now for the particulat format YYYY-MM-dd i don't want it to go for the check where we are prefixing 20 before in code please advise how can i skip that part lets say if the date pattern is YYYY-MM-dd then avoid the logic of prefixing 20 in front of year
below is my code
public java.util.Date extractDate(String dateStr, String dateType) {
String[] datePatternsOfUk = { "d-M-yy", "d-M-yyyy", "d/M/yy", "d/M/yyyy", "yyyy-MM-dd","dd-MM-yy", "dd-MMM-yy","dd-MMM-yyyy","dd-MM-yyyy",
"dd/MM/yy","dd/MMM/yy","dd/MMM/yyyy"};
String[] datePatternsOfUs = { "M-d-yy","MM-dd-yy","M/d/yy","MM/dd/yy", "MM/dd/yy", "MMM-dd-yy",
"MMM/dd/yy", "MMM-dd-yyyy", "MM-dd-yyyy", "MMM/dd/yyyy",
"MM/dd/yyyy" };
java.util.Date date = null;
String[] datePatterns = datePatternsOfUk;
if (dateType.equals("US")) {
datePatterns = datePatternsOfUs;
} else if (dateType.equals("UK")) {
datePatterns = datePatternsOfUk;
}
///******code should not go in this check where date pattern is YYYY-MM-dd
int p = dateStr.lastIndexOf("/");
if (p == -1) {
p = dateStr.lastIndexOf("-");
}
String firstSubstring = dateStr.substring(0, p + 1);
String secondSubstring = dateStr.substring(p + 1);
if (p != -1 && secondSubstring.length() <= 2) {
secondSubstring = Integer.toString(2000 + Integer.parseInt(secondSubstring));
dateStr = firstSubstring + secondSubstring;
}
///****************************************//
try {
date = DateUtils.parseDate(dateStr, datePatterns);
} catch (ParseException ex) {
logger.error("##$$$$$### Error in invoice inside extractDate method : ##$$$$$$#### "
+ ErrorUtility.getStackTraceForException(ex));
}
return date;
}
You could avoid trying any inappropriate pattern by checking if the string "looks like" the pattern before parsing with the pattern.
The general way to do this is:
String datePattern = "yyyy-MM-dd"; // for example
String input;
if (input.matches(datePattern.replaceAll("\\w", "\\d"))) {
// the input looks like the pattern
// in this example "dddd-dd-dd" where "d" is any digit
// so go ahead and try the parse
}
You can enhance this logic to add:
if (input.matches("\\d\\d\\D.*")) {
// then it only has a two digit year, so add "20" to the front
}
if (!dateStr.equals("YYYY-MM-dd")) {
// code
}

How to handle blank dates sent as parameters to Servlet

I'm writing a webapp where there are dates to be sent to a Servlet and I want to send some blank dates and based on these dates I want to build a query. But here My problem is when I pass the parameters i.e. the dates it's working fine, And when I send blank parameters it is throwing me the below error.
Start date got is and end date is //Here I'm checking the output
Unparseable date: "" servlet Errotr
When I give in the dates it shows in console as
Start date got is (TheStartDateValue) and end date is (TheEndDateValue)
and there is no exception (since the dates are parsed). And below is my code.
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
/* Date Start */
String startDateStr = request.getParameter("startDate");
String endDateStr = request.getParameter("endDate");
System.out.println("Start date got is " + startDateStr + " and end date is " + endDateStr);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat print = new SimpleDateFormat("yyyy-MM-dd");
Date startParsedDate = null, endParsedDate = null;
String startDate = null, endDate = null;
if (!startDateStr.equals(null) || !startDateStr.equals("")) {
startParsedDate = sdf.parse(startDateStr);
startDate = print.format(startParsedDate);
}
if (!endDateStr.equals(null) || !endDateStr.equals("")) {
endParsedDate = sdf.parse(endDateStr);
endDate = print.format(endParsedDate);
}
System.out.println(startDate + " value and " + endDate);
/* Date End */
DataDao dataDao = new DataDao();
ArrayList<UserBean> list = dataDao.getFrameWork(startDate, endDate);
String searchList = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(searchList);
System.out.println("servlet Done");
} catch (Exception e) {
System.err.println(e.getMessage() + " servlet Errotr");
}
}
I'm trying to handle the startDateStr and startDateStrto chweck if the input values are null or having some value using the below block in my above code.
if (!startDateStr.equals(null) || !startDateStr.equals("")) {
startParsedDate = sdf.parse(startDateStr);
startDate = print.format(startParsedDate);
}
if (!endDateStr.equals(null) || !endDateStr.equals("")) {
endParsedDate = sdf.parse(endDateStr);
endDate = print.format(endParsedDate);
}
Please let me know where am I going wrong and how can I fix this.
Thanks
Problem is in condition !startDateStr.equals(null) || !startDateStr.equals(""), you should change it to startDateStr != null && !startDateStr.equals("") and the same problem is in second condition.

Validating a Date in Java exactly like Oracle does in TO_DATE()

I have to Validate a date in Java to check if it is in correct format and correct value.
If I use SimpleDateformat Class, it will make wrong date valid as well because if a month is given as 14 it will add 1 year to the Year part.
However in Oracle it will indivisually check if Month , Date , Hour , Minute etc is correct.
E.g. in Oracle
TO_DATE(20141511 , 'YYYYMMDD')
will give error that the MONTH i.e. 15 is incorrect
But in Java
Date d = "YYYYMMDD".parse("20141511");
will be valid because it will count it as 2015+3 months.
So, how can I validate a date in Java exactly like Oracle does in its TO_DATE function?
If I understand your question, you could use DateFormat.setLenient(false). Per the JavaDoc,
Specify whether or not date/time parsing is to be lenient ... With strict parsing, inputs must match this object's format.
DateFormat df = new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
try {
Date d = df.parse("20141511");
} catch (ParseException e) {
e.printStackTrace();
}
Does not allow the invalid date to parse and throws
java.text.ParseException: Unparseable date: "20141511"
None of these solutions account Oracle settings for the date format. A more global solution using oracle.sql.Date and exceptions:
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import oracle.sql.DATE;
public void validateDate (String dateString, String nlsDateFormat, String nlsDateLanguage) throws ParseException, SQLException {
if (dateString == null) {
throw new ParseException("Date parameter not entered.", 0);
} else {
try {
DATE.fromText(dateString, nlsDateFormat, nlsDateLanguage); //not implemented in every ojdbc driver, works with ojbdbc6.jar
} catch (SQLException e) {
if (!e.getMessage().contains("Unimplemented")) {
throw new SQLException (e);
}
}
}
}
(I discovered some drivers couldn't even handle this.. so validation is bypassed if oracle.sql.DATE is not implemented)/ To get session variables for NLS_FORMAT and NLS_LANGUAGE:
private String getDateNlsFmt() throws SQLException {
String nlsDateFormat;
String sqlStmt =
"SELECT value nlsDateFormat "
+ " FROM nls_session_parameters "
+ " WHERE parameter = 'NLS_DATE_FORMAT' ";
QueryStatement q = new QueryStatement(conn, sqlStmt);
q.open();
if (!q.eof()) {
nlsDateFormat = q.getString("nlsDateFormat");
}
q.close();
return nlsDateFormat;
}
private String getDateNlsLang() throws SQLException {
String nlsDateLanguage;
String sqlStmt =
"SELECT value nlsDateLanguage "
+ " FROM nls_session_parameters "
+ " WHERE parameter = 'NLS_DATE_LANGUAGE' ";
QueryStatement q = new QueryStatement(conn, sqlStmt);
q.open();
if (!q.eof()) {
nlsDateLanguage = q.getString("nlsDateLanguage");
}
q.close();
return nlsDateLanguage;
}

Converting datepicker to string

How do you convert a DatePicker value to a String?
Currently I have a TextView setup, which the DatePicker passes its value to. Its displayed fine. Using that String to pass to a SQLite database isn't working however and returns
android.widget.TextView#41258880
When the databases fields are pulled up. I am currently taking the value and passing it to a string within the following TRY/Catch statement:
case R.id.btnUpdateDB:
boolean worked = true;
try {
String dbWeight = curWeight.getText().toString();
String dbWaist = curWaist.getText().toString();
String dbChest = curChest.getText().toString();
String dbLegs = curLegs.getText().toString();
String dbArms = curArms.getText().toString();
String dbDate = displayDate.toString();
Stats entry = new Stats(MainActivity.this);
entry.open();
entry.createEntry(dbWeight, dbWaist, dbChest, dbLegs, dbArms, dbDate);
entry.close();
break;
I feel that the following line is incorrect:
String dbDate = displayDate.toString();
You called the method toString directly on the widget. According to the source code it prints :
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
That's why you get :
android.widget.TextView#41258880
You have to do instead :
String dbDate = displayDate.getText().toString();
if displayDate is TextView You get its value just like You do with other fields before
String dbDate = displayDate.getText().toString();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
String dateFormat = dateformat.format(new Date(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()));

Check date format before parsing

I am parsing several documments with the field Duration. But in the differents files, it is in differnt formats, ex:
"Duration": "00:43"
"Duration": "113.046"
"Duration": "21.55 s"
I want to parse all of them to the format "Duration": "113.046", how could I check before any parsing in wich format it is??
Some conditions before this piece of code, because this is not right for all of them:
Long duration;
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
try {
Date durationD = sdf.parse(totalDuration);
Date zeroSec = sdf.parse("00:00:00");
duration = durationD.getTime() - zeroSec.getTime();
} catch (Exception e) {
duration = Long.parseLong(totalDuration);
}
Thanks in advance
You could match the pattern with help of regex and then format accordingly. Here's a kickoff example:
Map<Pattern, DateFormat> dateFormatPatterns = new HashMap<Pattern, DateFormat>();
dateFormatPatterns.put(Pattern.compile("\\d{1,2}:\\d{2}"), new SimpleDateFormat("H:m"));
dateFormatPatterns.put(Pattern.compile("\\d{1,3}\\.\\d{3}"), new SimpleDateFormat("s.S"));
dateFormatPatterns.put(Pattern.compile("\\d{1,2}\\.\\d{2} s"), new SimpleDateFormat("s.S 's'"));
String[] strings = { "00:43", "113.046", "21.55 s" };
DateFormat finalFormat = new SimpleDateFormat("HH:mm:ss");
for (String string : strings) {
for (Pattern pattern : dateFormatPatterns.keySet()) {
if (pattern.matcher(string).matches()) {
Date date = dateFormatPatterns.get(pattern).parse(string);
String formattedTime = finalFormat.format(date);
System.out.println(formattedTime);
break;
}
}
}
This yields here
00:43:00
00:01:53
00:00:21
If these are all your known input formats, then convert your input to your expected date format.
Just string-replace all : with . and remove s.
Do not forget to strip the spaces, too. By the way, "113.046" seems a bit odd date format to me - if I were in your shoes, I would have used some of the standard date time formats and convert the irregular ones.
My solution, not smart at all:
long DurationFixer(String duration){
long durationLong = 0;
if(duration.contains(":")){
DateFormat sdf = new SimpleDateFormat("mm:ss");
try {
Date durationD = sdf.parse(duration);
Date zeroSec = sdf.parse("00:00:00");
durationLong = durationD.getTime() - zeroSec.getTime();
} catch (Exception e) {
durationLong = (Long.parseLong(duration))/1000;
}
}
else{
String r = "";
if(duration.contains("s")){
for (int i = 0; i < duration.length()-2; i ++) {
if ((duration.charAt(i) == '.'))
break;
else
r += duration.charAt(i);
}
}
durationLong = Long.valueOf(r);
}
return durationLong;
}
If someone could find a better solution, please, tell me.
Thanks everybody!

Categories