My code like belows, I am using android. I found different devices may have different result.
Using different phone: I can get : "EST" or "GMT-05:00".
However, I just want to get abbreviation(just like "EST").
How can I get the abbreviation (or change offset to abbreviation)?
String timezone =Calendar.getInstance().getTimeZone().getDisplayName(false, TimeZone.SHORT);
If anyone else need the solution : I just tweak the code and get desired short name, which i needed to display to user.
private static String getTimeZoneShortName() {
String tz = TimeZone.getDefault().getDisplayName();
String[] stz = tz.split(" ");
StringBuilder sName = new StringBuilder();
for (int i = 0; i < stz.length; i++) {
sName.append(stz[i].charAt(0));
}
return sName.toString();
}
Related
Hello I am trying to store the birthdate of the user in database with the code below:
private void btnActionPerformed(java.awt.event.ActionEvent evt) {
String username = txtUserName.getText();
String password = txtPassword.getText();
String email = txtEmail.getText();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthdate = sdf.format(JDateChooser.getDate());
Users user = new Users();
user.setUserName(cin);
user.setPassWord(firstName);
user.setEmail(email);
user.setBirthDate(birthdate);
try {
int count = Users.getInstance().insert(user);
if(count == 1){
JOptionPane.showMessageDialog(null,"success");
reset();
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
I got an error which says String connot be converted to Date in the line "user.setBirthDate(birthdate);"
Because the parameter birthdate is assigned as Date type in the encapsulation(setBirthDate)
is there any way to solve this issue, I am new in java programming and I am trying to improve my skills in java.
If this returns a Date:
JDateChooser.getDate()
And what you need is a Date, then don't convert it to a String. Just keep it as a Date:
Date birthdate = JDateChooser.getDate();
// later...
user.setBirthDate(birthdate);
Note that you can then also remove this line, since you're not using the variable it declares:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
In general you want to keep data types in their raw form pretty much as often as possible. Unless there's a specific need for something to be represented as a string (displaying it to the user, sending it over a serialized API of some kind, etc.) then just use the data as-is instead of converting it to something else.
After you get the date with JDateChooser.getDate(), you are immediately converting it to a string: sdf.format(JDateChooser.getDate());
You should store the returned Date from JDateChooser.getDate() as an actual Date object.
Date birthdate = JDateChooser.getDate();
Then you can use it in your other function directly:
user.setBirthDate(birthdate);
If you do need the date as a string for some other purpose (perhaps display to the user), you can store a formatted string version in a different variable:
String birthdateString = sdf.format(birthdate);
Otherwise, if you don't need a string version, you can delete the line where you create sdf.
Is it possible to parse a delimited file and find column datatypes? e.g
Delimited file:
Email,FirstName,DOB,Age,CreateDate
test#test1.com,Test User1,20/01/2001,24,23/02/2015 14:06:45
test#test2.com,Test User2,14/02/2001,24,23/02/2015 14:06:45
test#test3.com,Test User3,15/01/2001,24,23/02/2015 14:06:45
test#test4.com,Test User4,23/05/2001,24,23/02/2015 14:06:45
Output:
Email datatype: email
FirstName datatype: Text
DOB datatype: date
Age datatype: int
CreateDate datatype: Timestamp
The purpose of this is to read a delimited file and construct a table creation query on the fly and insert data into that table.
I tried using apache validator, I believe we need to parse the complete file in order to determine each column data type.
EDIT: The code that I've tried:
CSVReader csvReader = new CSVReader(new FileReader(fileName),',');
String[] row = null;
int[] colLength=(int[]) null;
int colCount = 0;
String[] colDataType = null;
String[] colHeaders = null;
String[] header = csvReader.readNext();
if (header != null) {
colCount = header.length;
}
colLength = new int[colCount];
colDataType = new String[colCount];
colHeaders = new String[colCount];
for (int i=0;i<colCount;i++){
colHeaders[i]=header[i];
}
int templength=0;
String tempType = null;
IntegerValidator intValidator = new IntegerValidator();
DateValidator dateValidator = new DateValidator();
TimeValidator timeValidator = new TimeValidator();
while((row = csvReader.readNext()) != null) {
for(int i=0;i<colCount;i++) {
templength = row[i].length();
colLength[i] = templength > colLength[i] ? templength : colLength[i];
if(colHeaders[i].equalsIgnoreCase("email")){
logger.info("Col "+i+" is Email");
} else if(intValidator.isValid(row[i])){
tempType="Integer";
logger.info("Col "+i+" is Integer");
} else if(timeValidator.isValid(row[i])){
tempType="Time";
logger.info("Col "+i+" is Time");
} else if(dateValidator.isValid(row[i])){
tempType="Date";
logger.info("Col "+i+" is Date");
} else {
tempType="Text";
logger.info("Col "+i+" is Text");
}
logger.info(row[i].length()+"");
}
Not sure if this is the best way of doing this, any pointers in the right direction would be of help
If you wish to write this yourself rather than use a third party library then probably the easiest mechanism is to define a regular expression for each data type and then check if all fields satisfy it. Here's some sample code to get you started (using Java 8).
public enum DataType {
DATETIME("dd/dd/dddd dd:dd:dd"),
DATE("dd/dd/dddd",
EMAIL("\\w+#\\w+"),
TEXT(".*");
private final Predicate<String> tester;
DateType(String regexp) {
tester = Pattern.compile(regexp).asPredicate();
}
public static Optional<DataType> getTypeOfField(String[] fieldValues) {
return Arrays.stream(values())
.filter(dt -> Arrays.stream(fieldValues).allMatch(dt.tester)
.findFirst();
}
}
Note that this relies on the order of the enum values (e.g. testing for datetime before date).
Yes it is possible and you do have to parse the entire file first. Have a set of rules for each data type. Iterate over every row in the column. Start of with every column having every data type and cancel of data types if a row in that column violates a rule of that data type. After iterating the column check what data type is left for the column. Eg. Lets say we have two data types integer and text... rules for integer... well it must only contain numbers 0-9 and may begin with '-'. Text can be anything.
Our column:
345
-1ab
123
The integer data type would be removed by the second row so it would be text. If row two was just -1 then you would be left with integer and text so it would be integer because text would never be removed as our rule says text can be anything... you dont have to check for text basically if you left with no other data type the answer is text. Hope this answers your question
I have slight similar kind of logic needed for my project. Searched lot but did not get right solution. For me i need to pass string object to the method that should return datatype of the obj. finally i found post from #sprinter, it looks similar to my logic but i need to pass string instead of string array.
Modified the code for my need and posted below.
public enum DataType {
DATE("dd/dd/dddd"),
EMAIL("#gmail"),
NUMBER("[0-9]+"),
STRING("^[A-Za-z0-9? ,_-]+$");
private final String regEx;
public String getRegEx() {
return regEx;
}
DataType(String regEx) {
this.regEx = regEx;
}
public static Optional<DataType> getTypeOfField(String str) {
return Arrays.stream(DataType.values())
.filter(dt -> {
return Pattern.compile(dt.getRegEx()).matcher(str).matches();
})
.findFirst();
}
}
For example:
Optional<DataType> dataType = getTypeOfField("Bharathiraja");
System.out.println(dataType);
System.out.println(dataType .get());
Output:
Optional[STRING]
STRING
Please note, regular exp pattern is vary based on requirements, so modify the pattern as per your need don't take as it is.
Happy Coding !
I am a beginer in jquery and java.I have two string variables and a string array.I passed these 3 to a java servlet using a post request from javascript.Below is the code:
var stDate= $('#drpstart').jqxDateTimeInput('getText');
var edDate= $('#drpend').jqxDateTimeInput('getText');
var items = $("#target").jqxListBox('getItems');
var itemsid=[];
$("#jqxWidget").html('');
for (var i = 0; i < items.length; i++) {
itemsid[i]=items[i].value;
}
$.post('ActionItem',
{startdt:stDate,enddt:edDate,item:itemsid},function(responseJson) {
});
Then I access these variables and array at servlet side:
String starts=request.getParameter("startdt");
String ends=request.getParameter("enddt");
String[] myArray =request.getParameterValues("item");
if (myArray != null ) {
for (int i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
}
else {
System.out.println("null value");
}
but the myarray is geting a null value.How to get the values correctly to myarray?
Also my database table StockRegisterHeader contain field 'Date' with Date as datatype,so i converted the string variables starts and ends to Date format as below
SimpleDateFormat from = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat to = new SimpleDateFormat("yyyy-MM-dd");
Date startg = from.parse(starts); // 01/02/2014
Date endg = from.parse(ends);
Now I need to select data from 4 tables within this date range. I wrote the query as below:
String ss="SELECT Items.ParentID,Items.Name ,StockRegisterHeader.MovementType,
StockRegisterHeader.Date, UOM.Name,StockRegisterDetails.Quantity,
StockRegisterDetails.Rate from Items,StockRegisterHeader,UOM,StockRegisterDetails
where Items.ID = StockRegisterDetails.ItemID and
StockRegisterDetails.StockRegisterHeaderID = StockRegisterHeader.Id and
StockRegisterDetails.UOMID = UOM.ID and StockRegisterHeader.Date between '"+startg+"'
and '"+endg+"'";
rs=stmt.executeQuery(ss);
But the resultset object rs is showing null even if the database contain the requested data.I think this may be due to the date format. How to solve these two issues? I am using mysql database. Please help me.
try changing
String[] myArray =request.getParameterValues("item");
to
String[] myArray =request.getParameterValues("item[]"); //brackets must be specified to retrive array value
I want to convert a string into a date, this is simple. But what I'd like to do it without knowing the date format.
Here is a situation: say I have 100 dates and all are in the same format but I'd like to write a Java program to find out this format for me. The result of this program should give me a list of all the possible formats.
For example:
06-06-2006
06-06-2009
...
06-13-2001 <- 99th record
the result of this will give me date format can be mm-dd-yyyy
If the 99th record also was 06-06-2006 the result should be mm-dd-yyyy and dd-mm-yyyy.
Can someone please help me with an example?
Seems sensible to create a set of formats you know about (DATE_FORMATS) and then test each line to see which formats understand every line. You should end up with a set of possibilities.
public class DateFormatDetector {
private static final Set<String> DATE_FORMATS = new HashSet<String>();
static {
DATE_FORMATS.add("yyyy-MM-dd");
DATE_FORMATS.add("dd-MM-yyyy");
DATE_FORMATS.add("MM-dd-yyyy");
}
public static Set<String> getPossibleDateFormats(List<String> dates) {
Set<SimpleDateFormat> candidates = new HashSet<SimpleDateFormat>();
for (String df : DATE_FORMATS) {
SimpleDateFormat candidate = new SimpleDateFormat(df);
candidate.setLenient(false);
candidates.add(candidate);
}
for (String date : dates) {
Iterator<SimpleDateFormat> it = candidates.iterator();
while (it.hasNext()) {
SimpleDateFormat candidate = it.next();
try {
// try to parse the string as a date
candidate.parse(date);
}
catch (ParseException e) {
// failed to parse, so this format is not suitable
it.remove();
}
}
}
Set<String> results = new HashSet<String>();
for (SimpleDateFormat candidate : candidates)
results.add(candidate.toPattern());
return results;
}
}
Try to use SimpleDateFormat prepare all possible formats and calculate parsed result.
The solution could be functional Java as described for example in the stack overflow
I'm fairly new to programming in general and need some help.
I am using the Java.util.TimeZone to retrieve the IDs (city names) and their time zones. I am using a hashmap to implement this. I have put the city names and the time zones in the map and I am now trying to ask the user to enter a city they wish to get the time zone of.
However, in my loop I have a validation check to make sure the city name is in the hashmap. Not only is it not working but the loop also does not break. It correctly puts out the time it is currently but not the correct timezone for the city (I have typed various city names and all have about the same timezone). After printing out the local time it is in the city the user can choose to end the program by "saying yes".
If the user enters yes then the loop should break and the the program should end. If they enter anything else it should continue.
Could someone please help me fix this! Here is my code.
import java.util.*;
import java.util.TimeZone;
import java.util.Date;
import java.text.DateFormat;
import java.util.HashMap;
class Maps {
public static void main(String[] args) {
String[] Zone = TimeZone.getAvailableIDs();
int i = 0;
for (i = 0; i < Zone.length; i++) {
String zone1 = Zone[i].replaceAll("_", " ");
if (zone1.indexOf('/') != -1) {
zone1 = zone1.substring(zone1.indexOf('/') + 1);
}
TimeZone tz = TimeZone.getTimeZone(zone1);
HashMap hm = new HashMap();
HashMap<String, Integer> map = new HashMap<String, Integer>();
hm.put(zone1, tz);
// System.out.println(hm);
while (hm != null) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("City?");
String city = input.nextLine();
boolean CityExist = hm.containsKey(city);
if (CityExist == true) {
System.out
.println("I can not find a match to the city, sorry. ");
break;
}
TimeZone tz2 = TimeZone.getTimeZone(city);
DateFormat timeFormatter = DateFormat.getTimeInstance();
Date now = new Date();
System.out.println("Here: " + timeFormatter.format(now));
System.out.print("Local Time: ");
timeFormatter.setTimeZone(tz2);
System.out.println(timeFormatter.format(now));
System.out
.println("If you would like to quit please enter yes: ");
String user = input.nextLine();
if (user.equals("yes") || user.equals("Yes")) {
break;
}
}
}
}
}
Looks like you have the logic inverted: if CityExist then there was no match?
Please format your code next time.
Doing this, you will see that your first for loop is not closed and you are doing while loop still inside your for loop.
Solution, put the close bracket } before while loop.