Getting formatted date in date format rather than String - java

I'm running the program written below, but instead of printing in mm/dd/yyyy hh:mm format it prints in the normal date format(ie. Day Date and time)
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy hh:mm");
Date date = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
The reason i'm doing this is because the existing method accepts parameters in Date format, so i need to send the above mentioned date object to it.
Please point out the mistake or suggest some other alternative.
Thanks

Date objects don't have a format. The Date class is a wrapper around a single long, the number of milliseconds since the epoch. You can't "format" a Date, only a String. Pass around a Date/Calendar internally, and format it whenever you need to display it, log it, or otherwise return it to the user.

Change the format to MM/dd/yyyy. Month is denoted by capital M.
Check below URL for valid formats
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Your formatter works quite fine (apart from the mm vs. MM bug). You get a formatted string from the date and then create a copy from your date by parsing the formatted string:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
Date now = Calendar.getInstance().getTime();
String formattedNow = sdf.format(now); // == "09/24/2013 01:59"
Date now2 = sdf.parse(formattedNow); // == now

Related

How to print date string with ISO8601 format?

Please help me to print my date in below format
Example: 2020-08-05T16:17:10,777
I tried with below date converter but it is not giving the output that I want.
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String text = sdf.format(requestTime);
loggdata.append(REQUEST_TIME + requestDate);
I got date printed like "2020-08-20T06:26:09.003763Z". Date is in UTC tomezone and format is different.
I can see many question and answers here in stackoverflow. But here in my case I need exactly this format 2020-08-05T16:17:10,777 see the last portion ",777".
Also I need to display the time in local timezone
Found a solution for the same. I have used "LocalDateTime" for the same.
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss,SSS");
String dateInString= now.format(formatter);
It displayed date like this "2020-08-20T21:18:56,321"

Oracle Date Format change to yyyy-MM-dd hh:mm:ss

I have date saletime as 2/25/14 22:06 I want to store it in oracle table in the yyyy-MM-dd hh:mm:ss. So I wrote following java code
Date saleTime = sale.getSaleTime();
logger.info("DateTime is "+saleTime);
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date saleTimeNorm = formatter.parse(formatter.format(saleTime));
logger.info("DateTime after Formating "+saleTimeNorm);
Timestamp oracleDate = new Timestamp(saleTimeNorm.getTime());
logger.info("New Format Inserting :"+oracleDate);
sale.setSaleTime(oracleDate);
But this seems to be giving :0014-02-25 22:06:00.0
Any suggestions ?
Your getSaleTime() method somehow regards "14" as a four-digit year, and returns the year 14.
After you have executed getSaleTime(), you already have a Date variable; there is no need (and no use) in converting it to a different output format and re-parsing the result. The Date you get from the calls to format() and parse() will be the same one you started with.
You can create your Timestamp using getTime() on the result of the call to getSaleTime(). That will be correct once you change getSaleTime() so that it returns the date in the correct year.
Something must be wrong in your sale.getSaleTime() method. Because the following code working as needed.
Date saleTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date saleTimeNorm = formatter.parse(formatter.format(saleTime));
Timestamp oracleDate = new Timestamp(saleTimeNorm.getTime());
System.out.println(oracleDate);
//2014-05-13 03:58:53.0

Converting string into date type

I have used the Calendar class to get the current Date. Now I want to convert that date to Date format so that it can be stored in database with format "yyyy.mm.dd". I tried to convert this using SimpleDateFormat class
String dateString = dateText.getText();
SimpleDateFormat dateFormat = new SimpleDateFormat(" yyyy.mm.dd ");
Date convertedDate = dateFormat.parse(dateString);
but I couldn't convert into Date type.
Try to remove spaces from the format string
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.mm.dd");
Also if your input date has invalid format you might get a parse exception. Better if you put it into try/catch block.
Notice, that m stands for minute in hour but M for month of year. Make sure you put a valid format pattern.
You havent stated what the error is but its unlikely that you want to use a minute field to parse the month. Use uppercase M:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
get rid of the whitespaces in your pattern

change string to date as per the required date Format

I have to get a Date in type Date, not in String.
I have this code:
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date1 = new Date();
String date = (formatter.format(date1));
// At this point I get the date in correct format i.e 05/24/11
Date todaysDate = (Date)formatter.parse(date);
// But after this I get the date in format : Tue May 24 00:00:00 EDT 2011
// whereas I Want to get the date like above i.e 05/24/11
// And in type Date, not in type String
If anyone could help, thanks
The Date object just represents a point in time and has no notion of a format (or time zone). If you print out a Date object it first converts it to a String using the default formatting of EEE MMM dd HH:mm:ss zzz yyyy. If you want a specific formatting when you print it or otherwise represent it as a String, you'll need to use a formatter just like you already have.
In other words, you want Date.toString() to return the same as DateFormat.format()? You could just do exactly that:
public class MyDate extends Date {
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
public String toString() {
return this.formatter.format(this);
}
}
But do you really want to mix up presentation (date format) with your data?
There is no problem here, you have a Date representing and can save it into the DB as it is now. If you print it to the console it gets formatted according the default rules, this is why you think it is different from what you need, but it has actually already the right value.
So just go ahead and put it into your DB.
Chances are that you DB will hold on getting a Timestamp, in this case you can create one:
Date d = ...
java.sql.Timestamp ts = new java.sql.Timestamp(d.getTime());
and save this one.

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

I want to convert the timestamp 2011-03-10T11:54:30.207Z to 10/03/2011 11:54:30.207. How can I do this? I want to convert ISO8601 format to UTC and then that UTC should be location aware. Please help
String str_date="2011-03-10T11:54:30.207Z";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
date = (Date)formatter.parse(str_date);
System.out.println("output: " +date );
Exception :java.text.ParseException: Unparseable date: "2011-03-10T11:54:30.207Z"
Firstly, you need to be aware that UTC isn't a format, it's a time zone, effectively. So "converting from ISO8601 to UTC" doesn't really make sense as a concept.
However, here's a sample program using Joda Time which parses the text into a DateTime and then formats it. I've guessed at a format you may want to use - you haven't really provided enough information about what you're trying to do to say more than that. You may also want to consider time zones... do you want to display the local time at the specified instant? If so, you'll need to work out the user's time zone and convert appropriately.
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
String text = "2011-03-10T11:54:30.207Z";
DateTimeFormatter parser = ISODateTimeFormat.dateTime();
DateTime dt = parser.parseDateTime(text);
DateTimeFormatter formatter = DateTimeFormat.mediumDateTime();
System.out.println(formatter.print(dt));
}
}
Yes. you can use SimpleDateFormat like this.
SimpleDateFormat formatter, FORMATTER;
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String oldDate = "2011-03-10T11:54:30.207Z";
Date date = formatter.parse(oldDate.substring(0, 24));
FORMATTER = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
System.out.println("OldDate-->"+oldDate);
System.out.println("NewDate-->"+FORMATTER.format(date));
Output
OldDate-->2011-03-10T11:54:30.207Z
NewDate-->10-Mar-2011 11:54:30.207
Enter the original date into a Date object and then print out the result with a DateFormat. You may have to split up the string into smaller pieces to create the initial Date object, if the automatic parse method does not accept your format.
Pseudocode:
Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);
You might want to have a look at joda time, which is a little easier to use than the java native date tools, and provides many common date patterns pre-built.
In response to comments, more detail:
To do this using Joda time, you need two DateTimeFormatters - one for your input format to parse your input and one for your output format to print your output. Your input format is an ISO standard format, so Joda time's ISODateTimeFormat class has a static method with a parser for it already: dateHourMinuteSecondMillis. Your output format isn't one they have a pre-built formatter for, so you'll have to make one yourself using DateTimeFormat. I think DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS"); should do the trick. Once you have your two formatters, call the parseDateTime() method on the input format and the print method on the output format to get your result, as a string.
Putting it together should look something like this (warning, untested):
DateTimeFormatter input = ISODateTimeFormat.dateHourMinuteSecondMillis();
DateTimeFormatter output = DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS");
String outputFormat = output.print( input.parseDate(inputFormat) );
Hope this Helps:
public String getSystemTimeInBelowFormat() {
String timestamp = new SimpleDateFormat("yyyy-mm-dd 'T' HH:MM:SS.mmm-HH:SS").format(new Date());
return timestamp;
}
Use DateFormat. (Sorry, but the brevity of the question does not warrant a longer or more detailed answer.)

Categories

Resources