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);
}
}
Related
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));
}
}
Hi i am truing to convert this string 2015-11-26 to Date object so:
I am trying this:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date result=null;
try {
result = df.parse(date);
} catch (ParseException ex) {
Logger.getLogger(XmlReaderDemo.class.getName()).log(Level.SEVERE, null, ex);
}
codecurrency.setDate(result);
And date is the string holding 2015-11-26
It gives me exception and I don't know why.
Your code is working fine:
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.*;
import java.text.ParseException;
public class DateExample {
public static void main (String args[]) {
String date = "2015-11-26";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date result = null;
try {
result = df.parse(date);
} catch (ParseException ex) {
ex.printStackTrace();
}
System.out.println("result: " + result);
}
}
I just changed it a bit, so it compiles.
If you still can't get it to work, please post a Runnable example so we can provide more and better help.
This is the output I get:
result: Thu Nov 26 00:00:00 CST 2015
Also looking at the exception and your code, you probably want to move this line:
codecurrency.setDate(result);
inside the try call...
I have written few lines of code which reads data from the cookies stored in a text file and then write it on the web browser whenever required.
Block of code which i am using to store and write the cookies on a text file-
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class StoreCookieInfo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","D:\\Java Programs and files\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.facebook.com");
driver.findElement(By.name("email")).sendKeys("Your username");
driver.findElement(By.name("pass")).sendKeys("Your password");
driver.findElement(By.name("persistent")).click();
driver.findElement(By.name("pass")).submit();
File f = new File("browser.data");
try{
f.delete();
f.createNewFile();
FileWriter fos = new FileWriter(f);
BufferedWriter bos = new BufferedWriter(fos);
for(Cookie ck : driver.manage().getCookies()) {
bos.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()
+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));
bos.newLine();
}
bos.flush();
bos.close();
fos.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
It is running fine and storing data on text file.
Block of code which i am using to read cookies from the text file-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Date;
import java.util.StringTokenizer;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class LoadCookieInfo {
#SuppressWarnings("deprecation")
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver","D:\\Java Programs and files\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//WebDriver driver = new FirefoxDriver();
driver.get("http://www.facebook.com");
try{
File f2 = new File("browser.data");
FileReader fr = new FileReader(f2);
BufferedReader br = new BufferedReader(fr);
String line;
while((line=br.readLine())!=null){
StringTokenizer str = new StringTokenizer(line,";");
while(str.hasMoreTokens()){
String name = str.nextToken();
String value = str.nextToken();
String domain = str.nextToken();
String path = str.nextToken();
System.out.println("1");
Date expiry = null;
String dt;
if(!(dt=str.nextToken()).equals("null")){
expiry = new Date(dt);
}
boolean isSecure = new Boolean(str.nextToken()).booleanValue();
Cookie ck = new Cookie(name,value,domain,path,expiry,isSecure);
driver.manage().addCookie(ck);
System.out.println(name+value);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
driver.get("http://www.facebook.com");
}
}
When i am trying to run the second code i am getting the following exception on date -
java.lang.IllegalArgumentException
at java.util.Date.parse(Unknown Source)
at java.util.Date.<init>(Unknown Source)
at com.Selenium_Practice.LoadCookieInfo.main(LoadCookieInfo.java:39)
This is the first time i am trying to read data using cookies so i am not able to figure out what wrong i am doing in the code.
In java to convert a string into a date object use SimpleDateFormat Class.It is a concrete class for formatting and parsing dates.It allows you to start by choosing any user-defined patterns for date-time formatting
In the browser.data file the date is saved in format Sat Oct 03 01:12:17 IST 2015
So use a SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy")
E----->Day name in week(Sat)
MMM----->Month (Oct)
dd------>Day in month(03)
HH:mm:ss---->Hours:minutes:seconds(01:12:17)
Z----->Time Zone(IST)
yyyy---->Year(2015)
Date expiry = null;
SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
try {
String dt;
if(!(dt=str.nextToken()).equals("null")){
expiry = formatter.parse(dt);
System.out.println(expiry);
System.out.println(formatter.format(expiry));
}
} catch (ParseException e) {
e.printStackTrace();
}
I tested the above code it was working fine.I was able to add the cookie successfully after applying the above changes to LoadCookieInfo class
Hope this helps you...Kindly get back if you have any queries
The exception java.lang.IllegalArgumentException is thrown because you are passing String as a parameter to the Date constructor, that is deprecated and replaced by DateFormat.parse(String s).
String dt;
if(!(dt=str.nextToken()).equals("null")){
expiry = new Date(dt);
}
Try Using:
SimpleDateFormat formatter = new SimpleDateFormat("("E MMM dd HH:mm:ss Z yyyy")");
Date date = formatter.parse(dt);
There seems to be issue with your if condition also. (dt=str.nextToken()) will assign the value and give you true always, never equaling to null.
Let me know if it works with above solution.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TesterA
{
public static void main(String[] args)
{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try
{
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
}
catch (ParseException e)
{
e.printStackTrace();
}
}
}
I was trying to run this sample code copy from a web, but it doesn't work. How should I change it?
This is the error I got
java.text.ParseException: Unparseable date: "7-Jun-2013"
at java.text.DateFormat.parse(DateFormat.java:366)
at TesterA.main(TesterA.java:14)
I think it is a problem with your locale.
Try:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
java.text.ParseException means you provided a string which cannot be parsed using the current settings.
Just set the Locale.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
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"