How can I parse the following String "1394133302" which correspond of Date.toString value to a Date value (java utils).
Is it possible with a SimpleDateFormat?
Use code below
new Date(Long.valueOf("1394133302"))
PS. It seems you date string is in second, maybe you want this(convert it to millesecond!)
new Date(Long.valueOf("1394133302") * 1000L)
Just feed it back into the Date constructor:
long dateAsLong = Long.parseLong( "1394133302");
Date someDate = new Date(dateAsLong);
SimpleDateFormat is used for formatting Date value, in your case you already have a long date value in terms of Stringconvert it to Long and pass it directly to Date constructor to get date Object
Date dt = new Date(Long.valueOf("1394133302"));
Related
Bigquery.jobs().query().execute returns epoch time for timestamp and that epoch time includes dot with trailing alphanumeric value(1.295353708E9) thus converting that value to a Java timestamp fails;
Object v = checkNullAndGetColumnValue(columnIndex);
long epoch = Long.parseLong(v.toString());
String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
the returned value 1.295353708E9 is the same as 1295353708 however not sure what the best way to handle that as bq web UI renders it.
Any help highly appreciated!
I do this way
Calendar cal = Calendar.getInstance();
double d = Double.parseDouble("1.295353708E9");
long l = (long) d * 1000;
cal.setTimeInMillis(l);
String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(cal
.getTime());
Anyway, i think bigquery timestamp format is "YYYY-MM-dd HH:mm:ss.SSS"
This should work:
long epoch = Double.valueOf("1.295353708E9").longValue();
String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
.format(new Date (epoch*1000));
With the given example value, the date string resolves to 01/18/2011 21:28:28.
I want to convert the string time to Timestamp Object
My code for parsing is like this
String ts = "120918 10:35:45";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd hh:mm:ss");
java.util.Date parsedDate = dateFormat.parse(ts);
//parsing timestamp
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println("timestamp after parsing :: "+timestamp);
It gives me result :-- timestamp after parsing :: 2012-09-18 10:35:45.0
But I do not want milliseconds part. I want only this -- 2012-09-18 10:35:45
Please help me in removing milliseconds part.
Timestamp is a container of milliseconds. The toString() is formatting it's contains based on what it thinks is best to be displayed.
If you want to format the value, you should use a date formatter and not use the value returned by the Timestamp object.
SimpleDateFormat noMilliSecondsFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(noMilliSecondsFormatter.format(timestamp));
nb. The value you have (after you've converted it) does not contain any milliseconds anyway...
My guess, probably you didn't use "noMilliSecondsFormatter" in println().
The method java.util.Date.getTime() according to its javaDoc:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object
Therefore, when you create the TimeStamp object, you are already passing mileseconds.
I want to get the Date in MM/DD/YY format from a timestamp.
I have used the below method but it does not gives proper output
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(1306249409));
Log.d("Date--",""+cal.DAY_OF_MONTH);
Log.d("Month--",""+cal.MONTH);
Log.d("Year--",""+cal.YEAR);
But its gives the output like below
Date--5
Month--2
Year--1
The correct date is 24 May 2010 for Timestamp - 1306249409
Note - Timestamp is received by a webservice which is used in my application.
Better Approach
Simply Use SimpleDateFormat
new SimpleDateFormat("MM/dd/yyyy").format(new Date(timeStampMillisInLong));
Mistake in your Approach
DAY_OF_MONTH ,MONTH, .. etc are just constant int value used by Calendar class
internally
You can get the date represented by cal by cal.get(Calendar.DATE)
Use the SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String time = sdf.format(date);
What's wrong:
Calendar.DAY_OF_MONTH, Calendar.MONTH etc are static constants used to access those particular fields. (They will remain constant, no matter what setTimeInMillis you provide.)
How to solve it:
To get those particular fields you can use the .get(int field)-method, like this:
Log.d("Month--",""+cal.get(Calendar.MONTH));
As others have pointed out there are more convenient methods for formatting a date for logging. You could use for instance the SimpleDateFormat, or, as I usually do when logging, a format-string and String.format(formatStr, Calendar.getInstance()).
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
System.out.println(s);
TimeZone utc = TimeZone.getTimeZone("UTC"); // avoiding local time zone overhead
final Calendar cal = new GregorianCalendar(utc);
// always use GregorianCalendar explicitly if you don't want be suprised with
// Japanese Imperial Calendar or something
cal.setTimeInMillis(1306249409L*1000); // input need to be in miliseconds
Log.d("Date--",""+cal.get(Calendar.DAY_OF_MONTH));
Log.d("Month--",""+cal.get(Calendar.MONTH) + 1); // it starts from zero, add 1
Log.d("Year--",""+cal.get(Calendar.YEAR));
Java uses the number of milliseconds since 1st January 1970 to represent times. If you compute the time represented by 1306249409 milliseconds, you'll discover that it's only 362 days, so your assumptions are wrong.
Moreover, cal.DAY_OF_MONTH holds a constant. Use cal.get(Calendar.DAY_OF_MONTH) to get the day of month (same for other parts of the date).
use String.format which is able to convert long (milliseconds) to date/time string in different formats:
String str;
long time = 1306249409 * 1000L; // milliseconds
str = String.format("%1$tm/%1$td/%1$ty", time); // 05/24/11
str = String.format("%tF", time); // 2011-05-24 (ISO 8601)
str = String.format("Date--%td", time); // Date--24
str = String.format("Month--%tm", time); // Month--05
str = String.format("Year--%ty", time); // Year--11
documentation: format string.
I am using Java 6, and I have a time from the current date as a string, like this: 14:21:16, and I need to convert this to a Timestamp object to store in a database.
However there seems to be no good way to get a Timestamp from this. Timestamp.valueOf(String) is quite close, but requires a date. Is there a good way to make a Timestamp object from such a string?
How about this:
final String str = "14:21:16";
final Timestamp timestamp =
Timestamp.valueOf(
new SimpleDateFormat("yyyy-MM-dd ")
.format(new Date()) // get the current date as String
.concat(str) // and append the time
);
System.out.println(timestamp);
Output:
2011-03-02 14:21:16.0
Personally, I'd use Joda Time to parse the time to a LocalTime, and add that to today's LocalDate to get a LocalDateTime, then convert that into an Instant using whatever time zone you're interested in. (Or use LocalTime.toDateTimeToday(DateTimeZone).)
Then just create a time stamp using the Timestamp(long) constructor.
There are plenty of other approaches (e.g. using SimpleDateFormat instead of parsing with Joda Time, if you really want...) but ultimately you're likely to want the Timestamp(long) constructor in the end. (The benefit of using Joda Time here is that it's obvious what's being represented at each stage - you're not trying to treat a "time only" as a "date and time" or vice versa.)
Best I can come up with using standard API is not that pretty:
// Get today's date and time.
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date());
// Get the required time of day, copy year, month, day.
Calendar c2 = Calendar.getInstance();
c2.setTime(java.sql.Time.valueOf("14:21:16"));
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
// Construct required java.sql.Timestamp object.
Timestamp time = new Timestamp(c2.getTimeInMillis());
Let's see what we've done.
System.out.println(time);
Note that java.sql.Time.valueOf accepts a string of the form "HH:MM:SS" as you require. Other formats would require use of SimpleDateFormat.
Use org.apache.commons.lang.time.DateUtils:
Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
DateFormat df = new SimpleDateFormat("HH:mm:ss");
Date time = df.parse("14:21:16");
Timestamp time = new Timestamp(today.getTime() + time.getTime());
Have a given day (say, unix epoch?) to serve as the day. When you use it, only use the time parameters that you care about, ignoring the day.
Another option would be java.sql.Time
http://download.oracle.com/javase/1.4.2/docs/api/java/sql/Time.htm
String str = "14:21:16";
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date date = formatter.parse(str);
Timestamp timestamp = new Timestamp(date.getTime());
Can any body tell me how can I store Java Date to Mysql datetime...?
When I am trying to do so...only date is stored and time remain 00:00:00
in Mysql date stores like this...
2009-09-22 00:00:00
I want not only date but also time...like
2009-09-22 08:08:11
I am using JPA(Hibernate) with spring mydomain classes uses java.util.Date but i have created tables using handwritten queries...
this is my create statement
CREATE TABLE ContactUs (
id BIGINT AUTO_INCREMENT,
userName VARCHAR(30),
email VARCHAR(50),
subject VARCHAR(100),
message VARCHAR(1024),
messageType VARCHAR(15),
contactUsTime DATETIME,
PRIMARY KEY(id)
);
see in the link :
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
The following code just solved the problem:
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
This 'currentTime' was inserted into the column whose type was DateTime and it was successful.
Annotate your field (or getter) with #Temporal(TemporalType.TIMESTAMP), like this:
public class MyEntity {
...
#Temporal(TemporalType.TIMESTAMP)
private java.util.Date myDate;
...
}
That should do the trick.
Are you perhaps using java.sql.Date? While that has millisecond granularity as a Java class (it is a subclass of java.util.Date, bad design decision), it will be interpreted by the JDBC driver as a date without a time component. You have to use java.sql.Timestamp instead.
Probably because your java date has a different format from mysql format (YYYY-MM-DD HH:MM:SS)
do this
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
you will get 2011-07-18 + time format
long timeNow = Calendar.getInstance().getTimeInMillis();
java.sql.Timestamp ts = new java.sql.Timestamp(timeNow);
...
preparedStatement.setTimestamp(TIME_COL_INDEX, ts);
mysql datetime -> GregorianCalendar
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2012-12-13 14:54:30"); // mysql datetime format
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());
GregorianCalendar -> mysql datetime
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = format.format(calendar.getTime());
System.out.println(string);
java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());
preparedStatement.setObject(param);
Use the following code to insert the date into MySQL. Instead of changing our date's format to meet MySql's requirement, we can help data base to recognize our date by setting the STR_TO_DATE(?, '%l:%i %p') parameters.
For example, 2014-03-12 can be represented as STR_TO_DATE('2014-03-12', '%Y-%m-%d')
preparedStatement = connect.prepareStatement("INSERT INTO test.msft VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)");
Its very simple though conditions in this answer are in mysql the column datatype is datetime and you want to send data from java code to mysql:
java.util.Date dt = new java.util.Date();
whatever your code object may be.setDateTime(dt);
important thing is just pick the date and its format is already as per mysql format and send it, no further modifications required.
Actually you may not use SimpleDateFormat, you can use something like this;
#JsonSerialize(using=JsonDateSerializer.class)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
private Date blkDate;
This way you can directly get the date with format as specified.
I still prefer the method in one line
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())
If using java 8 or higher , try to use LocalDateTime. That was the correct type if you are using DATETIME as mysql data type.
Below is example for conver current time to "2009-09-22 08:08:11" format
LocalDateTime currentTime = LocalDateTime.parse(LocalDateTime.now().toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
it works for me !!
in mysql table
DATETIME
in entity:
private Date startDate;
in process:
objectEntity.setStartDate(new Date());
in preparedStatement:
pstm.setDate(9, new java.sql.Date(objEntity.getStartDate().getTime()));