I want to fetch records from database & want to set on form. In this form I am using JDateChooser from JCalendar. I have written the following code for this:
public void showdata()
int a=leaveView.getSelectedRow();
int b=(Integer)leaveView.getValueAt(a, 0);
String c=(String)leaveView.getValueAt(a, 1);
String d=(String)leaveView.getValueAt(a, 2);
String e=(String)leaveView.getValueAt(a, 3);
String f=(String)leaveView.getValueAt(a, 4);
String g=(String)leaveView.getValueAt(a, 5);
String h=(String)leaveView.getValueAt(a, 6);
int i=(Integer)leaveView.getValueAt(a, 7);
String j = (String)leaveView.getValueAt(a, 8);
String k = (String)leaveView.getValueAt(a, 9);
AL.empid.setSelectedItem(b);
AL.empname.setText(c);
AL.empname.setEditable(true);
AL.department.setText(d);
AL.department.setEditable(true);
AL.leavetype.setSelectedItem(e);
AL.other.setText(f);
AL.other.setEditable(true);
AL.jDateChooser1.setDate(g);
AL.jDateChooser2.setDate(h);
AL.noofdays.setText(""+i);
AL.noofdays.setEditable(true);
AL.singleday.setSelected(true);
AL.multipleday.setSelected(true);
}
but it's setting today's date to JDateChooser by default... it's not displaying the date which is retrieved from database... The above code is throwing an error at lines AL.jDateChooser1.setDate(g) and AL.jDateChooser2.setDate(h) for g & h...What can I do?
Assuming you are using this JCalendar API
From the javadocs setDate accepts a date object and not a string. First convert(parse) the dateString(g & h) to Date objects then set the date.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); //adjust this according to your requirement
Date gDate,hDate;
try {
gDate = df.parse(g);
hDate = df.parse(h);
} catch (ParseException e) {
e.printStackTrace();
}
AL.jDateChooser1.setDate(gDate);
AL.jDateChooser2.setDate(hDate);
for some example date formats,visit http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
Related
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..
I'm new to Android programming and I'm currently developing an app. Can someone help me on how to validate the date that is being input by the user if is it in range 7 days?
so, i have two string 'startDay' and 'endDay' where user input
startDay = 1/2/2017
endDay = 6/2/2017
then it went on the next step. and if user input
startDay = 1/2/2017
endDay = 9/2/2017 then it return message 'maximum 7 days'
there is the code that i made
#Override
public void onClick(View v) {
if (v==btnSearch){
String startDaystr = startDay.getText().toString();
String startMonthtstr = startMonth.getText().toString();
String endDaystr = endDay.getText().toString();
String endMonthstr = endMonth.getText().toString();
String endYearstr = endYear.getText().toString();
if(Integer.valueOf(startDaystr) >1 && Integer.valueOf(endDaystr) < 8){
sharedPreferenceCustom = SharedPreferenceCustom.getInstance(getContext());
sharedPreferenceCustom.putSharedPref("startDay", startDaystr);
sharedPreferenceCustom.putSharedPref("startMonth",startMonthtstr);
sharedPreferenceCustom.putSharedPref("endDay",endDaystr);
sharedPreferenceCustom.putSharedPref("endMonth",endMonthstr);
sharedPreferenceCustom.putSharedPref("endYear",endYearstr);
startActivity(new Intent(getActivity(), activity_history.class));
}else{
Toast.makeText(getActivity(), "Maximum 7 days!", Toast.LENGTH_LONG).show();
}
}
}
but when im input
startDay = 22/2/2017
endDay = 25/2/2017
the result is 'maximum 7 days' it should be return to the next step
please help me..im searched and tried also but not get such a solution..
I added startYearStr, please note that.
Use below code :
String startDaystr = startDay.getText().toString();
String startMonthtstr = startMonth.getText().toString();
String startYearstr = startYear.getText().toString();
String endDaystr = endDay.getText().toString();
String endMonthstr = endMonth.getText().toString();
String endYearstr = endYear.getText().toString();
Calendar startDate = Calendar.getInstance();
startDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(startDaystr));
startDate.set(Calendar.MONTH, Integer.parseInt(startMonthtstr));
startDate.set(Calendar.YEAR, Integer.parseInt(startYearstr));
startDate.set(Calendar.HOUR_OF_DAY, 0);
startDate.set(Calendar.MINUTE, 0);
startDate.set(Calendar.SECOND, 0);
Calendar endDate = Calendar.getInstance();
endDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(endDaystr));
endDate.set(Calendar.MONTH, Integer.parseInt(endMonthstr));
endDate.set(Calendar.YEAR, Integer.parseInt(endYearstr));
endDate.set(Calendar.HOUR_OF_DAY, 0);
endDate.set(Calendar.MINUTE, 0);
endDate.set(Calendar.SECOND, 0);
long diff = endDate.getTimeInMillis() - startDate.getTimeInMillis();
long dayCount = diff / (24 * 60 * 60 * 1000);
dayCount gives you the day difference between two dates.
To compare dates you would want to use the Java Date or Calendar objects but reading in the initial dates from an EditText like you are doing wouldn't be safe. If you aren't validating the input, a user could enter in something like "February 2nd 2016" when you are expecting "2/2/2016" so you might want to change it from a freeform EditText to a date picker so you can control how the user inputs the dates first.
Once you have the two dates in a supported Java object you can compare them against each other. This answer has an example how to do the comparison.
I am new to Java and to Google Script Editor. I have a custom CRM spreadsheet in google sheets, and would like to set up reminder emails based on regularly scheduled follow-up dates. I'm having trouble with the code. I think the trouble may be due to the fact that I'm trying to compare a date to a string, but I can't figure out how to get it to work.
The goal is to send off an email when the date for follow-up matches today's date. The date for follow-up is calculated based on a formula.
Even when the log reads:
[16-07-28 13:38:06:549 PDT] Date is Thu Jul 28 2016 00:00:00 GMT-0700 (PDT)
[16-07-28 13:38:06:549 PDT] Today is Thu Jul 28 2016 00:00:00 GMT-0700 (PDT)
My If statement if (date == todayFull) doesn't work. Here's the code:
function sendEmails() {
var ss = SpreadsheetApp.openById("number");
var sheet = ss.getSheetByName("Script");
var startRow = 2; // First row of data to process
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
// Fetch the range of cells
var dataRange = sheet.getRange(2, 1, lastRow, lastCol);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var date = row[32];
var todayFull = new Date();
todayFull.setHours(0);
todayFull.setMinutes(0);
todayFull.setSeconds(0);
Logger.log("Date is "+date);
Logger.log("Today is "+todayFull);
if (date == todayFull) {
Logger.log("This is a test. The Date is Today");
// var emailAddress = row[28]; // Email column
// var groupName = row[3]; // Group Name column
// var subject = "Follow up with this group right now!";
// MailApp.sendEmail(emailAddress, subject, groupName);
};
};
}
Thanks for the help. The first answer ended up working most of the way. Using .getDate() helped, but I also had to add arguments for month and year. Here's the code I ended up with:
function sendEmails() {
var ss = SpreadsheetApp.openById("");
var sheet = ss.getSheetByName("");
var startRow = 4; // First row of data to process
var lastRow = sheet.getLastRow(); //Get the last row of data to be processed
var lastCol = sheet.getLastColumn();
var dataRange = sheet.getRange(2, 1, lastRow-3, lastCol);
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var date2 = new Date(row[24]); // creates a new Date (date in string) object
var todayFull2 = new Date(); // creates a new Date (now) object
if (date2.getDate() == todayFull2.getDate() && date2.getMonth() == todayFull2.getMonth() && date2.getYear() == todayFull2.getYear()) {
etc
You're comparing two different data types:
var date = row[32]; // reads in a String object
var todayFull = new Date(); // creates a new Date (now) object
...
if (date == todayFull) { // compares Date with String
...
}
You might be better off creating the Date object when you read the value from your Sheet, and then comparing the actual dates in milliseconds (at time 00:00:00:00 of given date) of those Date objects, as you appear to be intending to do:
var date = new Date(row[32]); // creates a new Date (date in string) object
var todayFull = new Date(); // creates a new Date (now) object
todayFull.setHours(0,0,0,0) // sets time to midnight of current day
...
// compare Date with Date
if (date.getTime() == todayFull.getTime()) {
...
}
See MDN's excellent documentation on Javascript's Date.
I have a counter x that I want to invoke in two separate ActionListeners. When I try to make x into final, I can't increment using x++;. I tried to make x within the nest, but then I can't use the same value in the other ActionListener. Code is as follows:
buttonIn.addActionListener(new ActionListener() {
String reportDate = "";
int x = 0;
public void actionPerformed(ActionEvent e)
{
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date time = new GregorianCalendar().getTime();
reportDate = df.format(time);
String confirm = name.getText() + " has checked in at " + reportDate;
timeLabel.setText(confirm);
timeLabel.setVisible(true);
String action = "Time In";
reportData[x][0] = name.getText();
reportData[x][1] = "Time In";
reportData[x][2] = reportDate;
x++;
System.out.println(x);
}
});
buttonOut.addActionListener(new ActionListener() {
String reportDate = "";
public void actionPerformed(ActionEvent e)
{
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date time = new GregorianCalendar().getTime();
reportDate = df.format(time);
String confirm = name.getText() + " has checked out at " + reportDate;
timeLabel.setText(confirm);
timeLabel.setVisible(true);
reportData[x][0] = name.getText();
reportData[x][1] = "Time Out";
reportData[x][2] = reportDate;
x++;
}
});
One simple option is to use AtomicInteger instead - then the variable can be final, but you can still increment the wrapped value. So:
final AtomicInteger counter = new AtomicInteger(0);
buttonIn.addActionListener(new ActionListener() {
// Within here, you can use counter.get and counter.incrementAndGet
});
buttonOut.addActionListener(new ActionListener() {
// Within here, you can use counter.get and counter.incrementAndGet
});
I'd also strongly consider extracting that code into a separate class though - almost all the code is the same, so you should be able to remove the duplication by parameterizing the differences. So you'd end up with something like:
AtomicInteger counter = new AtomicInteger(0);
buttonIn.addActionListener(new ReportListener(
counter, reportData, "%s has checked in at %s", "Time In"));
buttonOut.addActionListener(new ReportListener(
counter, reportData, "%s has checked out at %s", "Time Out"));
(Where ReportListener is the new class implementing ActionListener.)
Additionally:
I strongly suspect you want to use HH rather than hh in your SimpleDateFormat
Consider which time zone and locale you want to use in your SimpleDateFormat, and specify them explicitly for clarity
To get the current time, just call new Date() rather than creating a calendar and extracting the date from it
There's no obvious reason for having reportDate as an instance variable
For testability, I'd encourage you to use some sort of Clock interface, with an implementation provided by dependency injection, so you can fake time appropriately
Consider using Joda Time for all date/time work; it's much cleaner than the built-in date/time API
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!