Get first element of ResultTable[] in java - java

These codes:
String genType = FileConstants.CHANGE_CYCLE;
ResultTable[] genericCode = RTManager.getRTCsmGenericCodesDecodeList(genType);
String genCode = Arrays.toString(genericCode);
Returns these values:
genCode = [[code=22:00:00]
[dCode=Cut-off time for change bill_cycle if existing cycle_close_date=activity_date]]
Question: how do i get only '22:00:00' and convert it as Time datatype?

If the item in the ResultTable array has a toString() and it produces string then you can get it like this.
genericCode[0].toString().split("=")[1]
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
String time = "22:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date;
try {
date = sdf.parse(time);
System.out.println("Time: " + sdf.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}

Related

How to compare to String Date Formats in java?

I am getting input as two types.
1.String date1 = "07/01/2017";
2.String date2 = ""2017-01-12 00:00:00.0";
How to compare two date formats. I want to perform one functionality if I get format as date1.If I get date2 format then Another functionality. How to compare two date formats using strings.
Ex:
if( date1.equals('dd/mm/yyyy')){
//perform functionality
}
Use RegEx:
String date1 = "07/01/2017";
if (date1.matches("^([0-9]{1,2}/){2}[0-9]{2,4}$")) {
System.out.println("Date in MM/dd/yyyy format");
} else if (date1.matches("^[0-9]{2,4}(-[0-9]{1,2}){2}\\s[0-9]{1,2}(:[0-9]{1,2}){2}\\.[0-9]{1,}$")) {
System.out.println("Date in yyyy-MM-dd hh:mm:ss.t format");
} else {
System.err.println("Unsupported Date format.");
}
If you want to know if the date is in format mm/dd/yyyy or mm-dd-yyyy or something in the same idea, you probably need to use regex expressions.
You can check this for a way to implement it What is the regular expression for Date format dd\mm\yyyy?
The solution with RegEx is good, but you can also do in this way:
The first parameter is your string representation of the date. The next parameter is var arg. So you can pass as many date formats as you wish. It will try to parse and if success then returns proper format.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Optional<String> format = test("07-01-2017", "dd/mm/yyyy", "dd-mm-yyyy");
if (format.isPresent())
System.out.println(format.get());
}
public static Optional<String> test(String date, String... formats) {
return Stream.of(formats)
.map(format -> new Pair<>(new SimpleDateFormat(format), format))
.map(p -> {
try {
p._1.parse(date);
return p._2;
} catch (ParseException e) {
return null;
}
})
.filter(Objects::nonNull)
.findFirst();
}
public static class Pair<F, S> {
public final F _1;
public final S _2;
public Pair(F _1, S _2) {
this._1 = _1;
this._2 = _2;
}
}
}
I guess, we can declare two date formats and parse the dates and compare the two Date instances. Here is sample code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCompare {
private static final String FORMAT1 = "MM/dd/yyyy";
private static final String FORMAT2 = "yyyy-MM-dd hh:mm:ss";
private Date parseDate(String format1, String format2, String dateStr) throws ParseException {
boolean isException = false;
Date date = null;
try {
date = parseDate(format1, dateStr);
} catch (ParseException e) {
isException = true;
}
if (isException) {
date = parseDate(format2, dateStr);
}
return date;
}
private Date parseDate(String format1, String dateStr) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat(format1);
return dateFormat.parse(dateStr);
}
public static void main(String[] args) throws ParseException {
DateCompare compare = new DateCompare();
Date date1 = compare.parseDate(FORMAT1, FORMAT2,"07/01/2017");
Date date2 = compare.parseDate(FORMAT1, FORMAT2, "2017-07-01 00:00:00");
if (date1.compareTo(date2) == 0) {
System.out.println("Dates are equal.");
} else {
System.out.println("Dates are not equal.");
}
}
}

Formatting XMLGregorianCalendar

I want to convert a string that contains a date to a GregorianCalendar in the form "dd.mm.yyyy".
I have used the below code. I am able to convert to the desired datatype, but not in the desired format.
Any suggestions regarding this would be helpful to me.
public class StringToCalander {
public static void main(String args[]) throws DatatypeConfigurationException {
String date="20160916";
Date dob=null;
DateFormat df=new SimpleDateFormat("yyyyMMdd");
try {
dob=df.parse( date );
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dob);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
System.out.println(" xml date value is:"+xmlDate);
//output is 2016-09-16T00:00:00.000+02:00
//but i need output in the format dd.mm.yyyy(16.09.2016)
}
}
Try this. (updated for GregorianCalendar as well)
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class StringToCalendar {
public static void main(String args[])
throws DatatypeConfigurationException {
String FORMATER = "ddMMyyyy";
DateFormat format = new SimpleDateFormat(FORMATER);
Date date2 = new Date();
XMLGregorianCalendar gDateFormatted = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(format.format(date2));
System.out.println("xmlDate via GregorianCalendar: " + gDateFormatted);
}
}
You can use a Date-Object to format your XMLGregorianCalendar:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Main {
public static void main(String args[])
throws DatatypeConfigurationException {
String format = "dd'.'MM'.'yyyy";
DateFormat formatter = new SimpleDateFormat(format);
GregorianCalendar date = new GregorianCalendar();
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(date);
Date dateObject = xmlDate.toGregorianCalendar().getTime();
System.out.println("xml date value is: " + formatter.format(dateObject));
}
}

Convert String to Timestamp Java

So I am having this issue that I can't wrap my head around. I've read similar questions posed but very case I've found there is an issue with the format, and my format is correct.
Basically I am trying to convert a String into a Timestamp, and I get the unparseable date error.
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Hello {
public static Timestamp convertStringToTimestamp(String str_date) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
Date date = formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
}
public static void main(String[] args) {
Timestamp ts = convertStringToTimestamp("2015-06-09 11:51:12,708");
Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564");
System.out.println(ts +" | "+ts2);
}
}
Output:
Exception :java.text.ParseException: Unparseable date: "2015-06-09 11:51:12,708"
Exception :java.text.ParseException: Unparseable date: "2015-04-17 11:29:49.564"
null | null
Any ideas?
This works perfectly to me.
I just passed the right pattern as an input as well.
public static Timestamp convertStringToTimestamp(String str_date, String pattern) {
try {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
Date date = formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
return timeStampDate;
} catch (ParseException e) {
System.out.println("Exception :" + e);
return null;
}
}
public static void main(String[] args) {
Timestamp ts = convertStringToTimestamp("2015-06-09 11:51:12,708", "yyyy-MM-dd HH:mm:ss,SSS");
Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564", "yyyy-MM-dd HH:mm:ss.SSS");
System.out.println(ts +" | "+ts2);
}
The output is:
2015-06-09 11:51:12.708 | 2015-04-17 11:29:49.564
"2015-06-09 11:51:12,708" is working for me but "2015-04-17 11:29:49.564" won't. You specified the regex for "," so "." would not. It is perfectly normal.
you need to fix the comma
Timestamp ts2 = convertStringToTimestamp("2015-04-17 11:29:49.564");
**Update**
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SomeClass {
public static void main(String[] args) {
System.out.println(convertStringToTimestamp("2015-06-09 11:51:12,708"));
//be consistent here with , and .
System.out.println(convertStringToTimestamp("2015-04-17 11:29:49.564"));
System.out.println();
}
private static Timestamp convertStringToTimestamp(String something) {
SimpleDateFormat dateFormat = null;
if(something.contains(".")) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
}
if(something.contains(",")) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
}
Timestamp timestamp = null;
Date parsedDate;
try {
parsedDate = dateFormat.parse(something);
timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return timestamp;
}
}

Java Timestamp to MySQL Timestamp

I have this code, but it is not working. I have Error message:
"com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column 'Datum_zalozeni' at row 1"
pstmt = conn.prepareStatement(INSERT);
Timestamp ts = u.getDatum_zalozeni();
System.out.println(ts);
pstmt.setTimestamp(1, ts);
pstmt.setInt(2, u.getId_klient());
pstmt.executeUpdate();
My database is:
CREATE TABLE Ucet
(
Id_Uctu Int NOT NULL auto_increment primary key,
Datum_zalozeni Timestamp NOT NULL,
Id_klient Int NOT NULL
)
;
Where is mistake? I think code is correct.
I have a code to generate the System Timestamp. It sets 0 in place of 979. Have a look.
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimestampTest
{
public static void main(String[] args)
{
try
{
System.out.println("System Date: " + generateTimestamp("yyyy-MM-dd HH:mm:ss"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static Timestamp generateTimestamp(String format)
{
Timestamp timestamp = null;
try
{
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
Date date = dateFormat.parse(generateDate(format));
timestamp = new Timestamp(date.getTime());
}
catch (ParseException e)
{
e.printStackTrace();
}
return timestamp;
}
public static String generateDate(String format)
{
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat(format);
return (dateFormat.format(date));
}
}
MySQL usually accepts Timestamps in the format '2013-12-06 14:24:34'. It would be helpful if you share what is the exact value you are trying to insert into the database.
Timestamp ts = u.getDatum_zalozeni();
System.out.println(ts);
pstmt.setTimestamp(1, ts);
What is ts?

Can't import data from excel file

I am getting an error( Unparseable date: "18–11–2003") when i try to import data from excel file. the date from the file cannot be parsed
if(row.getCell(16)!=null){
String dobb=null;
Date dob=null;
row.getCell(16).setCellType(row.getCell(16).CELL_TYPE_STRING);
dobb=row.getCell(16).getStringCellValue();
System.out.println(dobb);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
dob = (Date)simpleDateFormat.parse(dobb);//error..... Unparseable date: "18–11–2003"
System.out.println("dateeee"+dob);
} catch (ParseException e) {
e.printStackTrace();
//dob=new Date();
}
It looks like the specified "18–11–2003" date contains u2013 Unicode character instead of a normal dash which is u002d.
Here is a sample that uses the string copy-pasted from the question:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDate {
public static void main(String[] args) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
String trouble = "18–11–2003";
String goodOne = "18-11-2003";
Date date = simpleDateFormat.parse(goodOne);
//Date date = simpleDateFormat.parse(trouble);
System.out.println(String.format ("\\u%04x", (int)trouble.charAt(2)));
System.out.println(String.format ("\\u%04x", (int)goodOne.charAt(2)));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
The character in the actual date (–) is not the same character in your date format (-).
This code:
public static void main(String[] args) {
System.out.println((int)'–');
System.out.println((int)'-');
}
produces this result:
8211
45
There are several things you can do:
Do a replace() on your date string (dateStr = dateStr.replace("–", "-");) to replace the strange hyphen with an actual ASCII hyphen. *Recommended*
Change your dateformat from "dd–MM–yyyy" to "dd–MM–yyyy"

Categories