Formatting XMLGregorianCalendar - java

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));
}
}

Related

Get first element of ResultTable[] in 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();
}
}
}

generating Unique transaction code/reference in java

want to generate unique transaction code/reference like "2016100000223433" in java.
Requirements,
human readable(not too long)
use time,year, date
use primary key in database table(optional)
unique
Is there any method in java which can use ?
After getting others ideas created this mechanism. Is this suitable for this problem?
import java.util.Date;
import java.util.Calendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.TimeZone;
import java.util.Random;
public class Transaction {
public static void main(String args[]) {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
try {
Thread.sleep(1);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
Calendar requestCal = Calendar.getInstance();
requestCal.setTime(date);
String newOne = requestCal.getWeekYear() + "" + String.format("%15s", requestCal.getTimeInMillis()+"").replace(' ', '0');
System.out.println(newOne);
}
}

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;
}
}

How to convert one formatted date String to another format

I have a JDateChooser bean panel named basDate. When i execute System.out.println(basDate.getText()); it returns 12.02.2014 But i must convert and edit it to 2014-02-12 00:00:00.000
Just i want edit and assign new output to a variable coming as "12.02.2014" value as "2014-02-12 00:00:00.000"
I use Netbeans Gui Builder.
Since the input date is a string in a different format from what you want, you need to two SimpleDateFormats. One to parse the String to a Date and another to format the Date to a different format.
Test this out. input 12.02.2014 output 2014-12-02 00:00:00:000
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyDateFormat {
public static void main(String[] args){
String inputStringDate = "12.02.2014";
SimpleDateFormat inputFormat = new SimpleDateFormat("dd.MM.yyyy");
Date inputDate = null;
try {
inputDate = inputFormat.parse(inputStringDate);
} catch (ParseException ex) {
Logger.getLogger(MyDateFormat.class.getName()).log(Level.SEVERE, null, ex);
}
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss:SSS");
String outputStringDate = outputFormat.format(inputDate);
System.out.println(outputStringDate);
}
}

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