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

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

Related

Convert milliseconds to timestamp with UTC

I'm trying to convert milliseconds to Timestamp with timezone UTC but it doesn't work as is expected because it convert to my localdatetime.
I have tried following. While debugging the code I have found that when execute this: new DateTime(eventDate) it is working properly because it's value is 10:34:18.721 but later new Timestamp() change it to localdatetime.
long eventDate = 1566297258721L;
DateTimeZone.setDefault(DateTimeZone.UTC);
Timestamp timestamp = new Timestamp(new DateTime(eventDate).getMillis());
I expect to output as:2019-08-20 10:34:18.721 but actual output is: 2019-08-20 12:34:18.721
You can use java.time package of Java 8 and later:
ZonedDateTime zonedDateTime = Instant.ofEpochMilli(1566817891743L).atZone(ZoneOffset.UTC);
I don't understand why you are creating a new DateTime and then get the milliseconds from there, if you already have the milliseconds in the beginning.
Maybe I'm misunderstanding your problem. The milliseconds have nothing to do with the timezone. The timezone is used to compare the same moment in 2 different places and get the respective date. Here are my solutions
If you want a timestamp from milliseconds:
long eventDate = 1566297258721L;
Timestamp time=new Timestamp(eventDate);
System.out.println(time);
The result would be 2019-08-20 10:34:18.721 , also the wished SQL format
If you want to convert a moment from a Timezone to another:
You will get the moment in your actual timezone and transform it in a different one in order to see e.g. what time it was in an other country
long eventDate = 1566297258721L;
Calendar calendar = Calendar.getInstance();
calendar.setTime(eventDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dateFormat.format(calendar.getTime());
I hope those snippets could be useful. Happy Programming!
You can try the following,
long eventDate = 1566297258721L;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String stringDate = simpleDateFormat.format(new Date(eventDate));
System.out.println(stringDate);
It gives me the following output.
2019-08-20 10:34:18 UTC

How to get the correct format of dateand time in mysql?

When I get the date and time in MySQL it retrieves it in this format:
2016-01-14 14:24:00.0
Where does the .0 come from and how do I get this format with Java:
2016-01-14 14:24:00
You can use 2 ways to do this.
Split the date string at '.'
String date = "2016-01-14 14:24:00.0";
String newDate = date.split("\\.")[0];
System.out.println(newDate);
Use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdf.parse("2016-01-14 14:24:00.0");
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
If you are getting date as string, you can use Format to get the format you need:
SELECT DATE_FORMAT(YourDateField, '%d-%m-%Y %T')
FROM YourTable
Have a look here for all possible formats
If you are getting your date as a java.sql.Timestamp, you can get the corresponding java.util.Date instance very easily and then format it to the desired string representation with a java.text.SimpleDateFormat class.

How do I format a java.sql.date into this format: "MM-dd-yyyy"?

I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.
This is what I have tried so far:
java.util.Date
today=new Date();
String date = formatter.format(today);
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime());
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate);
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate);
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);
You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
10-31-2014
Use below code i have convert today date. learn from it and try with your code
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in MM-dd-yyyy format : " + date);
Date date1 = formatter.parse(date);
System.out.println(date1);
System.out.println(formatter.format(date1));
A simpler solution would be to just convert the date in the query to epoch before comparing.
SELECT date_column from YourTable where UNIX_TIMESTAMP(date_column) > ?;
Then, simply pass date.getTime() when binding value to ?.
NOTE: The UNIX_TIMESTAMP function is for MySQL. You'll find such functions for other databases too.
java.util.Date today=new Date();
java.sql.Date date=new java.sql.Date(today.getTime()); //your SQL date object
SimpleDateFormat simpDate = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(simpDate.format(date)); //output String in MM-dd-yyyy
Note that it does not matter if your date is in format mm-dd-yyyy or any other format, when you compare date (java.sql.Date or java.util.Date) they will always be compared in form of the dates they represent. The format of date is just a way of setting or getting date in desired format.
The formatter.parse will only give you a java.util.Date not a java.sql.Date
once you have a java.util.Date you can convert it to a java.sql.Date by doing
java.sql.Date sqlDate = new java.sql.Date (normalDate.getTime ());
Also note that no dates have any built in format, it is in reality a class built on top of a number.
For anyone reading this in 2017 or later, the modern solution uses LocalDate from java.time, the modern Java date and time API, instead of java.sql.Date. The latter is long outdated.
Formatting your date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.US);
LocalDate fromDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
String tempFromDate = fromDate.format(formatter);
System.out.println(tempFromDate);
This prints something like
11-25-2017
Don’t confuse your date value with its textual representation
Neither a LocalDate nor a java.sql.Date object has any inherent format. So please try — and try hard if necessary — to keep the two concepts apart, the date on one side and its presentation to a user on the other.
It’s like int and all other data types. An int can have a value of 4284. You may format this into 4,284 or 4 284, 004284 or even into hex representation. This does in no way alter the int itself. In the same way, formatting your date does not affect your date object. So use the string for presenting to the user, and use LocalDate for storing into your database (a modern JDBC driver or other modern means of database access wil be happy to do that, for example through PreparedStatement.setObject()).
Use explicit time zone
Getting today’s date is a time zone sensitive operation since it is not the same date in all time zones of the world. I strongly recommend you make this fact explicit in the code. In my snippet I have used Asia/Kolkata time zone, please substitute your desired time zone. You may use ZoneId.systemDefault() for your JVM’s time zone setting, but please be aware that this setting may be changed under our feet by other parts of your program or other programs running in the same JVM, so this is fragile.

Getting formatted date in date format rather than String

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

java Date and time format

how to format "2011-10-25T13:00:00Z" string into date and time
i used simple date format class
SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
but it only giving the date value. not time values
please help me to solve this problem
Use the format "yyyy-MM-dd'T'HH:mm:ss'Z'" for parsing this date format. See the documentation of SimpleDateFormat for more info. Code will look like this
String dateStr = "2011-09-19T15:57:11Z";
String pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
Date date = new SimpleDateFormat(pattern).parse(dateStr);
This is because "yyyy-MM-dd" only mentions year (yyyy), month (MM) and date (dd). Try adding hh:mm if you want hours and minutes.
Example:
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm");
System.out.println(sim.format(new Date())); // prints "2011-10-27 01:56"
The full documentation of the format-string and its parts is found here. The documentation includes this example:
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" - 2001-07-04T12:08:56.235-0700
Perhaps it's something like that you're looking for.

Categories

Resources