Split a date and inserting it to a web form - java

I have a Date in string format "01-23-2004".
I want to split the date and insert every day/month/year to a different filed in a web form.
I did this:
public static void dateInString()
{
String dt = "01-23-2004";
String dateParts[] = dt.split("-");
String month = dateParts[0];
String day = dateParts[1];
String year = dateParts[2];
}
public void insertBirthDateBounus() throws IOException, ParserConfigurationException, SAXException
{
comOps.selectDropDown(birthdayMonth,day);
comOps.selectDropDown(birthdayDay, mounth);
comOps.selectDropDown(birthdayYear, year);
}
And I received an error msg that day, mounth, year - cant be resolved by variable.
( comOps.selectDropDown is the select from drop down list to select a date. This was written in a different class with all my common methods )

Use like this .
1.Let month 、day and year as global variables
2.Use it in insertBirthDateBounus method
private static String month;
private static String day;
private static String year;
public static void dateInString() {
String dt = "01-23-2004";
// 1.format first
SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy",Locale.ENGLISH);
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM-dd-yyyy",Locale.ENGLISH);
Date date = null;
try {
date = sdf1.parse(dt);
String newDate= sdf2.format(date);
System.out.println(newDate);
// 2.split
String[] dateParts = newDate.split("-");
month = dateParts[0];
day = dateParts[1];
year = dateParts[2];
System.out.println(month);
} catch (ParseException e) {
e.printStackTrace();
}
}
public void insertBirthDateBounus() throws IOException, ParserConfigurationException, SAXException {
comOps.selectDropDown(birthdayMonth, day);
comOps.selectDropDown(birthdayDay, month);
comOps.selectDropDown(birthdayYear, year);
}

Related

How to set a predefined message in lblText.steText()

I want to got the String msg from where Exception is thrown in personAge method so it shows defined error for a person.
How do I get the message from throw new Invalid..("the message");
to the lable?
This is code in my controler
#FXML
void btnRegister(ActionEvent event) {
String name = txtName.getText();
String email = txtEmail.getText();
String phonenr = txtPhonenr.getText();
int year = Integer.parseInt(txtYear.getText());
int month = Integer.parseInt(txtMonth.getText());
int day = Integer.parseInt(txtDay.getText());
boolean validateName = PersonValidator.checkName(name);
boolean validateEmail = PersonValidator.checkEmail(email);
boolean validatePhonenr = PersonValidator.checkPhonenr(phonenr);
try{
PersonAge.personAge(year);
}catch (InvalidAgeException msg){
lblResult.setText(msg);
}
}
And this is where exceptions is thrown :
public class PersonAge {
public static int personAge(int year) throws InvalidAgeException {
Date date = new Date();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Norway"));
cal.setTime(date);
int thisYear = cal.get(Calendar.YEAR);
int age = thisYear - year;
if(age <=0 || age > 120){
throw new InvalidAgeException("Age is invalid! Try again");
}
return age;
}
}
You just need to call getMessage() on the exception: lblResult.setText(msg.getMessage());

Getting Blank Date as string from a custom date method

I am making a date filter for which I have created a custom method for date to be parse in specific date format.
I have date with to two formats dd MMM yyyy & yyyy-mm-dd which is passed in a single method to be parse and return in format of yyyy-mm-dd. As I have a complex structure at end both type of formatted string will go under the date parsing method.
ISSUE:: I am getting a blank string as return from this method when format is in yyyy-mm-dd. please provide me inputs of where i am wrong. Below is the code
//fetching date from methods
String current_date=CurrentFilterPeriod.dateParsing("2017-04-02");
String prev_date=CurrentFilterPeriod.dateParsing("01 Apr 2017");
//singleton file for date filter method
public class CurrentFilterPeriod {
private static Calendar cal = getInstance();
private static Date current_date = cal.getTime();
//defined formats for date
private static SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
private static SimpleDateFormat formatterString = new SimpleDateFormat("yyyy-MM-dd");
//method for parsing date
public static String dateParsing(String date){
Date newDate;
String returnDate = "";
if (date.equals(formatter.toPattern())){
returnDate=date;
}
Log.e("DB","date===>"+date);
try {
newDate = formatter.parse(date);
Log.e("DB","New Date===>"+newDate);
returnDate=formatterString.format(newDate);
Log.e("DB","returnDate===>"+returnDate);
} catch (ParseException e) {
e.printStackTrace();
}
return returnDate;
}
}
RESULT:: current_date="" prev_date="2017-04-01"
I am stuck here please help me or tell me other methods to get by desired output.Want result in format of yyyy-mm-dd
As you want result format like: yyyy-mm-dd. You need to check your Date String with formatterString formatter.
Change your code with:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
boolean isValidDate(String input) {
try {
format.parse(input);
return true;
}
catch(ParseException e){
return false;
}
}
Now call the method using:
//method for parsing date
public static String dateParsing(String date) {
Date newDate;
String returnDate = "";
if (isValidDate(date)) {
returnDate = date;
return returnDate;
} else {
Log.e("DB", "date===>" + date);
try {
newDate = formatter.parse(date);
Log.e("DB", "New Date===>" + newDate);
returnDate = formatterString.format(newDate);
Log.e("DB", "returnDate===>" + returnDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
return returnDate;
}

How to change GMT to PST format in Java?

I have a code that displays time in GMT and I need to show it in PST. How can I modify the below code to get the time in PST?
Code
public static final String FORMAT = "MM/dd/yyyy";
public static final String OUTPUT_FORMAT_STD_DATE6 = "MM/dd/yy hh:mm a";
public static final String INPUT_FORMAT_STD_TIMESTAMP = "yyyy-MM-dd HH:mm:ss";
public static String formatDate(String strDate, String inputFormat, String outputFormat) {
Date date = convertStringToDate(strDate,inputFormat);
String displayDateString = formatDate(date, outputFormat);
return displayDateString;
}
formatDate is being called here
public void endElement(String uri, String localName, String qName) throws SAXException {
if( EVENT.equalsIgnoreCase( qName ) ) {
auditEntries.add(entry);
} else if( LOG_TIME.equalsIgnoreCase( qName ) ) {
String time = content.toString();
entry.setLogTime( DateUtils.formatDate(time, "yyyy-MM-dd'T'HH:mm:ss", DateUtils.OUTPUT_FORMAT_STD_DATE6));
}
Please help, I am new b in writing Java code.
This is how I am doing it.
public static String formatDate(String strDate, String inputFormat, String outputFormat) {
Date date = convertStringToDate(strDate,inputFormat);
DateFormat pstFormat = new SimpleDateFormat( outputFormat );
pstFormat.setTimeZone( TimeZone.getDefault() );
String displayDateString = formatDate(date, outputFormat);
return displayDateString;
}
Thanks
Once you have a Date object you can convert it to a timezoned string using SimpleDateFormat. Below is a simple example.
Using 3 letter timezone IDs has been deprecated, so you should use GMT+-hour:minute format, or region specific string like America/Los_Angeles as suggested by #VGR
For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.
Ref:https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class DateTest {
public static final String OUTPUT_FORMAT_STD_DATE6 = "MM/dd/yy hh:mm a";
public static void main(String[] args) {
Date date = new Date();
String gmtDateStr = dateToTimzoneString(date, "GMT", OUTPUT_FORMAT_STD_DATE6);
System.out.println(gmtDateStr);
//3 Letter String usage is deprecated
String pstDateStr = dateToTimzoneString(date, "PST", OUTPUT_FORMAT_STD_DATE6);
System.out.println(pstDateStr);
//Correct way
pstDateStr = dateToTimzoneString(date, "GMT+5", OUTPUT_FORMAT_STD_DATE6);
System.out.println(pstDateStr);
}
public static String dateToTimzoneString(Date date, String timeZoneStr, String outputFormat){
SimpleDateFormat sd = new SimpleDateFormat(outputFormat);
sd.setTimeZone(TimeZone.getTimeZone(timeZoneStr));
return sd.format(date);
}
}
This is how I did it.
public static String convertUTC( String strDate, String inputFormat, String outputFormat ) {
String displayDateString = null;
try {
DateFormat inFormat = new SimpleDateFormat( inputFormat );
inFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
Date date = inFormat.parse( strDate );
DateFormat outFormat = new SimpleDateFormat( outputFormat );
outFormat.setTimeZone( TimeZone.getDefault() );
displayDateString = formatDate(date, outputFormat);
} catch ( ParseException pe ) {
pe.printStackTrace();
}
return displayDateString;
}

java.lang.NullPointerException when parsinng date

I am getting exception when sending request from my rest client
This is my DTO class
private String fromDate;
private String toDate;
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
request packet is this format how to send date in this format but it will take as String
{
" toDate": "2014/07/01",
" fromDate ": "2014/05/01",
" imeiNo ": "1234567890",
" phoneNumber ": 1234567890,
" emailId ": ""
}
here is my method for converting in helper class
private static Timestamp convertStringDateToTimestamp(String stringDate)
{
DateFormat formatter;
Date date = null;
formatter = new SimpleDateFormat("yy-MM-dd");
try {
date = (Date) formatter.parse(stringDate);
}
catch (ParseException e) {
e.printStackTrace();
}
java.sql.Timestamp timeStamp = new Timestamp(date.getTime());
return timeStamp;
}
but getting this exception in my server
java.lang.NullPointerException at org.omnypay.mobileapp.webservices.helper.TransactionHelper.convertStringDateToTimestamp(Tra
Please help me
If the formatter does not parse the string as a date, the date variable is null and you cannot call date.getTime().
Add a null check before that line.
OR
As Jon says, you need to handle the Exception better. Either throw the exception once you have printed the stacktrace, or return a value so that the program execution does not continue to the rest of the method.
Your date have / as separator but you are defining - as a separator in your formatter. And also you have full year like 2014 not 14 Change it to
formatter = new SimpleDateFormat("yyyy/MM/dd");

Formatting and validating a date in JSF

So I want to format my dateinputfield as "dd-MM-yyyy" and then validate that the date is not before tomorrow.
This is the relevant code in my view:
<h:inputText id="dueDate" required="true" value="#{submitRepairBean.dueDate}">
<f:convertDateTime pattern="dd-MM-yyyy"/>
<f:validator validatorId="be.kdg.repaircafe.validators.DueDateValidator"/>
</h:inputText>
This is my custom validator:
#FacesValidator("be.kdg.repaircafe.validators.DueDateValidator")
public class DueDateValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
System.out.println(value.toString()); //For some reason this prints Wed Jul 23 02:00:00 CEST 2014 when inputting 23-07-2014
DateTime date = new DateTime(value.toString());
long dueDateMillis = date.getMillis();
long oneDayMillis = 86400000;
Calendar tomorrowMidnight = new GregorianCalendar();
// reset hour, minutes, seconds and millis
tomorrowMidnight.set(Calendar.HOUR_OF_DAY, 0);
tomorrowMidnight.set(Calendar.MINUTE, 0);
tomorrowMidnight.set(Calendar.SECOND, 0);
tomorrowMidnight.set(Calendar.MILLISECOND, 0);
tomorrowMidnight.add(Calendar.DAY_OF_MONTH, 1);
if (dueDateMillis + oneDayMillis < tomorrowMidnight.getTimeInMillis()) {
throw new ValidatorException(new FacesMessage("You can not have something repaired before tomorrow!"));
}
}
Now the thing I don't understand is why it doesn't print in the converted format (dd-MM-yyyy), even then I don't care so much as long as I get the correct amount of milliseconds.
However, the DateTime constructor then throws an exception that the date is in an invalid format.
I've tried using SimpleDateFormat as well, with no luck.
The converter it will show you the date in this format on the page (in the jsp/html page). What it does, is converting the date in a string in the format dd-mm-yyyy. When you pass the calue in the validate function, it is not converted in the string in the format dd-MM-yyyy. it is a date, dueDate is a date, so by printing value.toString() is just converts the date value to a string. So the object is a date and just by casting to Date is should work. if you want in the code to print it in the format dd-MM-yyyy try this
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String strDate = sdf.format(date);
System.out.println(strDate );
#FacesValidator("validator.dateValidator")
public class DateValidator implements Validator, ClientValidator {
final static String DATE_FORMAT = "dd-MM-yyyy";
public DateValidator() {
}
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null || StringUtils.isEmpty((String) value.toString())) {
return;
}
SimpleDateFormat objDf = new SimpleDateFormat(DATE_FORMAT);
objDf.setLenient(false);
try {
try {
Date data = new Date();
data.setDate(data.getDate() + 1);
if(objDf.parse(value.toString()).before(data)){
((UIInput) component).setValid(false);
throw new ValidatorException(new FacesMessage("You can not have something repaired before tomorrow!"));
}
} catch (ParseException e) {
((UIInput) component).setValid(false);
throw new ValidatorException(new FacesMessage(MessageUtils.ALERTA, "Data informada não Válida!", ""));
}
} catch (ParseException e) {
throw new ValidatorException(new FacesMessage("Invalid Date!"));
}
}
public Map<String, Object> getMetadata() {
return null;
}
public String getValidatorId() {
return "validator.dateValidator";
}
}

Categories