I tacked this problem in VB awhile back, and thought I could easily translate it to Java. The input comes in as a string in the format:
"mm/dd/yyyy"
I want to change this to the following format:
"mm/dd/yy"
where the last two year digits are shown only. I wrote this VB awhile back, which does just that:
Function DateFormat(ByVal myDate As String) As String
Dim reformat As Date
reformat = Date.Parse(myDate, Nothing)
Return Format(reformat, "MM/dd/yy").ToString()
End Function
How can I do this exact same thing in Java, so that the date is reformatted correctly and returned as the string it originally was? I have something like this but it is not working properly:
public static String DateFormat(String myDate){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try{
Date formattedDate = formatter.parse(myDate);
return formattedDate.toString();
}catch(Exception e){
e.printStackTrace();
return null;
}
}
I am not sure how to make it the format I need, as I can't find anything similar to the Format() function VB has. Thanks in advance.
Try this :
public static String DateFormat(String myDate) throws ParseException {
SimpleDateFormat inFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat outFormat = new SimpleDateFormat("MM/dd/yy");
Date parsedInDate = inFormat.parse(myDate);
return outFormat.format(parsedInDate);
}
At start, we declare two date formatters, then we create Date object from input String, and at the end we produce String in new format.
If I understand your question, you could use a pair of SimpleDateFormat(s)
private static final String formatIn = "MM/dd/yyyy";
private static final String formatOut = "MM/dd/yy";
private static final DateFormat sdfIn = new SimpleDateFormat(
formatIn);
private static final DateFormat sdfOut = new SimpleDateFormat(
formatOut);
public static String formatDateString(String dateIn)
throws ParseException {
return sdfOut.format(sdfIn.parse(dateIn));
}
public static void main(String[] args) {
try {
System.out.println(formatDateString("07/15/2014"));
} catch (ParseException e) {
e.printStackTrace();
}
}
Output is
07/15/14
SimpleDateFormat takes in a number of different formats. I believe the format you want is already built in and can be accessed like so...
Date date = new Date();
Format formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
System.out.println(s);
You've basically almost got it, just need to apply the new format.
public static String DateFormat(String myDate){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try{
Date date = formatter.parse(myDate);
formatter.applyPattern("MM/dd/yy");
return formatter.format(date);
}catch(Exception e){
e.printStackTrace();
return null;
}
}
Related
I have a project requirement. There are values in a .txt as -
02/01/2017 00:00:00
Now I need to have some rules to check if this value in the data file is of type Date. How can I do that? Thanks. I am new to Java so any help much appreciated. Thanks
Try to parse it to date. If it throws ParseException then it is not a date.
String dateString = "02/01/2017 00:00:00";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
Date date;
try {
date = df.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
If you just want valid days, use non-lenient parsing:
String dateString = "02/28/2017 00:00:00";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
df.setLenient(false);
Date date;
try {
date = df.parse(dateString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
This will throw an exception for non-existing days like the 31st of February
Methord 1
Date dt = new Date(); //this should your Dynamic object
if (dt.getClass().equals(new Date().getClass()))
{
//if its date object
}
Methord 2
if(dt instanceof Date){
//if its date object
}
Use this to check date
String sDate1="31/12/1998 00:00:00";
try{
Date date1=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse(sDate1); `
}
catch(Exception e)
{
//Not a date..
}
You can use regular expressions to check the format
public boolean isDate(String s){
String pattern= "([0-9]{2})/([0-9]{2})/([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})";
return s.matches(pattern);}
Here’s the Java 8 solution (it can be made to work in Java 6 and 7 too when you use the ThreeTen Backport).
private static final DateTimeFormatter DATE_TIME_FORMAT
= DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss")
.withResolverStyle(ResolverStyle.STRICT);
public static boolean hasTypeDate(String stringFromTxt) {
try {
DATE_TIME_FORMAT.parse(stringFromTxt);
return true;
} catch (DateTimeParseException dtpe) {
return false;
}
}
Stay away from SimpleDateFormat for new code. It has had its time, it’s been outdated for a while now.
If you intended the day of month first (if 02/01/2017 means January 2nd), you need the format pattern dd/MM/uuuu HH:mm:ss instead.
If you need to know which date and time was in the .txt, use:
LocalDateTime dateTime = LocalDateTime.parse(stringFromTxt, DATE_TIME_FORMAT);
Link: ThreeTen Backport: java.time classes for Java 6 and 7.
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static void main(String[] args) {
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
isValidDate(line));
//do what you want :)
}
I am using MongoDB to save my data and in database i can see the date value like this
ISODate("2016-11-30T11:17:20.945Z")
but when i parse it in front-end it become like
createdOn : 1480582463992
I want to convert "ISODate("2016-11-30T11:17:20.945Z")" it in JAVA and not in js in such a way so that i can get string date value.
Thanks in advance
==============================================================
here is my java code
#Override
public List<Prescription> getcus(
String id, String cid) {
List<Prescription> listrescription = null;
listrescription = this.patientDBService.getPatientLastThreePrescription(id, cid);
Prescription prre = new Prescription();
for(Prescription i : listrescription){
//Date dates = new Date();
//i.getCreatedOn(); // getting the data from mongo like 1480582463992
//no clue what to do here to get ISO date as in string
}
return listrescription;
}
try this:
new Date("2016-11-30T11:17:20.945Z")
If you don't care about the time zone you can use this method to parse the date format like "2017-06-19T05:27:26.000Z"
private static String convertMongoDate(String val){
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat= new SimpleDateFormat("yyyy/MM/dd");
try {
String finalStr = outputFormat.format(inputFormat.parse(val));
System.out.println(finalStr);
return finalStr;
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
I am trying to use SimpleDateFormat.parse method to parse a date string to Date object, but it is omitting "T" in the final date that is returned. I am passing this date string 2015-04-15T12:55:07.365 and I am getting 2015-04-15 12:55:07.365 in the output. However, the desired output is 2015-04-15T12:55:07.365.
Why is "T" in the final output omitted by this line parsedDate = sdf.parse(transDate);
public static void main(String[] args)
{
try
{
final String pattern = "yyyy-MM-dd'T'hh:mm:ss.SSS"; // example 2015-04-15T12:55:07.365
final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String transDate = "2015-04-15T12:55:07.365";
Date parsedDate = sdf.parse(transDate);
System.out.println("transDate:"+transDate+", parsedDate: "+parsedDate);
}
You never get your desired output 2015-04-15T12:55:07.365
Why?
Because you are printing Date object parsedDate.Date class has it's own toString() method implementation.When you are printing the date object, it means it basically prints the toString() method implementation format.
see the Java doc for details
System.out.println(parsedDate) would give you Wed Apr 15 00:55:07 GMT 2015 which is the toString() representation of the date object.
You can use SimpleDateFormat to parse AND format dates:
SimpleDateFormat sdfParser = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
Date date = sdfParser.parse("2015-04-15T12:55:07.365");
SimpleDateFormat sdfFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
String formattedDate = sdfFormatter.format(date);
System.out.println(formattedDate);
// 2015-04-15T12:55:07.365
You will get desired output here.
public static void main(String args[]) {
{
try {
String transDate = "2015-04-15T12:55:07.365";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
Date date = sdf.parse(transDate);
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date d = sdf.parse(sdf.format(date));
String formattedTime = output.format(d);
System.out.println("transDate:" + transDate + ", parsedDate: " + formattedTime);
} catch (Exception e) {
}
}
}
I have this string: 7 -Jun- 2014.
I want to convert to java.utils.Date;
I use this Code
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/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();
}
but I get this exception :
java.text.ParseException: Unparseable date: "7-Jun-2013"
at java.text.DateFormat.parse(Unknown Source)
at ma.abcsolution.util.Test.main(Test.java:15)
try using
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
the SimpleDateFormat look at the given string like it you tell it to, so in your example it look for a string with 2 chars for days, followed by a '/' sign and then 2 chars for month and so on
Using SimpleDateFormatter you can convert from date string to date and date to date String
public final class DateUtil {
private static final String DEFAULT_DATE_FORMAT = "dd-MMM-yyyy";
private DateUtil() {
}
public static final String formatDate(final Date date, final String dateFormat) {
DateFormat format = new SimpleDateFormat(dateFormat, Locale.ENGLISH);
return format.format(date);
}
public static final Date formatDate(final String date) throws ParseException {
return formatDate(date, DEFAULT_DATE_FORMAT);
}
public static final Date formatDate(final String date, final String dateFormat) throws ParseException {
DateFormat format = new SimpleDateFormat(dateFormat);
return format.parse(date);
}
}
Whenever you are going yo format date please verify the format you are using
In your case you used dd/MM/yyyy but date you used in format dd-MMM-yyyy.
Use
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
to format the date. You used the wrong format with the / signs.
See also:
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Date date = new SimpleDateFormat("d-MMM-yyyy").parse("7-Jun-2014");
Use this code. It is simple.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTime {
public static void main(String args[]){
SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "7-Jun-2013";
Date date=new Date(dateInString);
System.out.println(ft.format(date));
}
}
In mysql, i have a field time_entered of type datetime (sample data: 2012-06-20 16:00:47). I also have a method, getTimeEntered(), that returns the value as String. I want to display the date in this format 2012-06-20 using DateTimeFormat from GWT.
here's my code:
String date = aprHeaderDW.getTimeEntered();
DateTimeFormat fmt = DateTimeFormat.getFormat("MM-dd-yyyy");
dateEntered.setText("" + fmt.format(date));
The problem is, the format method doesn't accept arguments as String. So if there's only a way I could convert the date from String to Date type, it could probably work. I tried typecasting but didn't work.
You should be able to just use DateTimeFormat.
Date date = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
String dateString = DateTimeFormat.getFormat("yyyy-MM-dd").format(date);
Otherwise there is a light-weight version of SimpleDateFormat that supports this pattern.
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
Hi There are two options.
The first is as it is already a string you could use a regular expression to modify the format.
The second is using a SimpleDateFormater you can parse the string to a date then back again.
For example:
public class DateMerge {
public static void main(String arg[])
{
String out = dateConvert("2012-06-20 16:00:47");
System.out.println(out);
}
public static String dateConvert (String inDate)
{
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = (Date)formatter.parse(inDate);
formatter = new SimpleDateFormat("dd-MM-yyyy");
String outDate = formatter.format(date);
return outDate;
} catch (ParseException e)
{System.out.println("Exception :"+e); }
return null;
}
}
You may use like this.
String date = "2012-06-20 16:00:47";
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
String lDate=sf.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
System.out.println(lDate);
Output:
2012-06-20
After trying a lot of times I came up with a solution, based on #Keppil and adding my own code.
Here's Keppil's suggested solution for converting String datetime into Date type:
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
...but my second requirement is to display just the date like 2012-06-20. Even though I removed HH:mm:ss, it still displayed the time like this 2012-06-20 00:00:00.
Here's my final solution:
Date date = null;
String d = rs.getString(SQL_CREATION_TIME); // assigns datetime value from mysql
// parse String datetime to Date
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(d);
System.out.println("time entered: "+ date);
} catch (ParseException e) { e.printStackTrace(); }
// format the Date object then assigns to String
Format formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);