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);
}
}
Related
I have a code which is shown as follows. But it has error, which is indicated as "error line". The error message is:
java.lang.NoClassDefFoundError: ParseException.
Can anyone help me fix the error? Thank you so much!
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.*;
public class TestCalendar2 {
public static void main(String[] args) throws ParseException{ // error line
String str = "2020-10-10";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("df:" + df);
Date date = df.parse(str);
System.out.println("date:" + date);
Calendar c = new GregorianCalendar();
System.out.println("c:" + c);
c.setTime(date);
System.out.println("Sunday\t一\t二\t三\t四\t五\t六");
c.set(Calendar.DAY_OF_MONTH,1);
for(int i = 0; i < c.get(Calendar.DAY_OF_WEEK)-1;i++) {
System.out.print("\t");
}
for (int i=1; i<=c.getActualMaximum(Calendar.DATE); i++) {
System.out.print(c.get(Calendar.DAY_OF_MONTH)+"\t");
if(c.get(Calendar.DAY_OF_WEEK)== Calendar.SATURDAY) {
System.out.println();
}
c.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
You need import it:
import java.text.ParseException;
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();
}
}
}
I'm trying to convert a string date to a an object date.
It works perfectly if i use a string, but when i read the string date from a file, the result is ko.
On forums, i have found the cause may come from zone. It is still KO.
I'm unable to say why the dateformat rise an exception. :o(
A snippet of my code :
package main;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
public class dateTestConv {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String dateOK1 = new String("21/01/2017");
convertDateStringEuroToDateObject(dateOK1);
String dateOK2= "21/01/2017";
convertDateStringEuroToDateObject(dateOK2);
//From file =KO
collectDateFromFile();
}
public static Date convertDateStringEuroToDateObject(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",Locale.FRANCE);
Date d = null;
try {
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
d = dateFormat.parse(date);
} catch (ParseException ex) {
Logger.getLogger(dateTestConv.class.getName()).log(Level.SEVERE, null, ex);
}
return d;
}
public static void collectDateFromFile(){
String dirName=new String("dates.txt");
File file = new File(dirName);
try {
FileInputStream fstreami = new FileInputStream(dirName);
DataInputStream in = new DataInputStream(fstreami);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String dateFormatNormal = strLine;
Date d0= convertDateStringEuroToDateObject(dateFormatNormal);
}
in.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The file dates.txt contains just one line :
21/01/2017
When the method collectDateFromFile() is called , this exception is rised :
SEVERE: null
java.text.ParseException: Unparseable date: "21/01/2017"
at java.text.DateFormat.parse(DateFormat.java:366)
at main.dateTestConv.convertDateStringEuroToDateObject(dateTestConv.java:52)
at main.dateTestConv.collectDateFromFile(dateTestConv.java:75)
at main.dateTestConv.main(dateTestConv.java:42)
Thanks for your help.
Simply put, the string is not what you think it is. So you need to debug it by comparing the received with the expected value. For example, if there is an unexpected unicode codepoint hiding in there, you might detect it like this:
String dateFormatNormal = strLine;
/* Debug: is there an unexpected unicode codepoint hiding in there? */
System.out.println("Received: " + dateFormatNormal.codePoints()
.mapToObj(i -> String.format("0x%04x (%s)", i, String.valueOf(Character.toChars(i))))
.collect(Collectors.toList()));
System.out.println("Expected: " + "21/01/2017".codePoints()
.mapToObj(i -> String.format("0x%04x (%s)", i, String.valueOf(Character.toChars(i))))
.collect(Collectors.toList()));
/* Remove Debug code when done */
It could be due to space in string. Try trim on string and then parse
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));
}
}
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);
}
}