Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have two date objects.
Date d1;
Date d2;
My program stores in d1, the date in the format 'dd/MM/yyyy' and in d2 in the format 'HH:mm'.
I would now like to combine these information and create a new Date object with the format 'dd/MM/yyyy HH:mm'.
Any pointers on how can I achieve so?
-V
If you are indeed using Date objects, just set the time of d1 to match that of d2.
d1.setHours(d2.getHours());
d1.setMinutes(d2.getMinutes());
Or make a new Date object if you don't want to use d1. Just parse it afterwards with SimpleDateFormat.
Note however that this is deprecated and it's better to use Calendar for this.
First, most of functionality of Date is deprecated. Use Calendar instead. Second, to parse and create string representation of date use SimpleDateFormat.
I hope these tips are enough to start. There are a lot of references in net and javadoc to continue. Good luck.
You cannot use Date for this purpose. You should instead use Calendar (from JDK) or joda-time.
try out this..
String dateValue= new java.util.Date().toString();
String concat like this..
String newDateTime = d1+""+d2+":00";
Try this
DateFormat df1=new SimpleDateFormat("dd/MM/yyyy");
DateFormat df2=new SimpleDateFormat("HH:mm");
Date d1=df1.parse("09/07/2013");
Date d2=df2.parse("14:43");
String d=df1.format(d1).toString()+" "+df2.format(d2).toString();
DateFormat newDate=new SimpleDateFormat("dd/MM/yyyy HH:mm");
System.out.println(newDate.format(newDate.parse(d)));
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
i want to get the day of month of a date in java
i try getday() but it return day of week
for (int i =0; i<count; i++) {
series1.add(new Task(Names.get(i),
Date.from(LocalDate.of(Dates.get(j).getYear(), Dates.get(j).getMonth(),Dates.get(j).getDay()).atStartOfDay().toInstant(ZoneOffset.UTC)),
Date.from(LocalDate.of(Dates.get(k).getYear(),Dates.get(k).getMonth(),Dates.get(k).getDay()).atStartOfDay().toInstant(ZoneOffset.UTC))
)
);
j+=2;k+=2;
}
I looked into your previous Stack Overflow question for some context. Please don’t expect that Stack Overflow users will usually do this. They will not.
As I understand it, Task is org.jfree.data.gantt.Task from JFreeChart, and its constructor requires two java.util.Date arguments (start and end). You are getting java.sql.Date objects from your database.
While you cannot (reasonably) change JFreeChart, since JDBC 4.2 you can take advantage of getting modern LocalDate objects rather than old-fashioned java.sql.Date objects from your database:
while (rs.next()) {
String a = rs.getString("TITRE");
LocalDate startDate = rs.getObject("DATE DEBUT Prévi", LocalDate.class);
LocalDate endDate = rs.getObject("DATE FIN prévi", LocalDate.class);
series1.add(new Task(a,
Date.from(startDate.atStartOfDay().toInstant(ZoneOffset.UTC)),
Date.from(endDate.atStartOfDay().toInstant(ZoneOffset.UTC))
)
);
}
I found it simpler not to put your fetched data into separate lists and taking it out again before constructing the Task objects. In your code please do as you find best.
PS The getXxx methods of java.sql.Date and java.util.Date are deprecated because they work unreliably across time zones, so even if you couldn’t avoid those classes, never call those methods. If you do get a java.sql.Date from somewhere, the first thing to do is call its toLocalDate method to convert it to a modern LocalDate.
EDIT: You are doing very much in a single statement with nested method calls. I agree with the comment by Basil Bourque that this can be hard for a reader (and yourself?) to follow. I believe that this was also part of why people (including myself) didn’t understand your question. We suggest breaking it up. One example would be:
Instant startInstant = startDate.atStartOfDay().toInstant(ZoneOffset.UTC);
Date startUtilDate = Date.from(startInstant);
// Similarly for end date
Task newTask = new Task(a, startUtilDate, endUtilDate);
series1.add(newTask);
It’s wordier, but each step is easy to follow now.
Instead of startDate.atStartOfDay().toInstant(ZoneOffset.UTC) I usually do startDate.atStartOfDay(ZoneOffset.UTC).toInstant(), but that’s a matter of taste or habit. The result is the same in both cases.
Links
Your previous Stack Overflow question: how can i draw gantt chart with date from database in java
Documentation of the org.jfree.data.gantt.Task(String, Date, Date) constructor
I am assuming Dates is a Map so Dates.get(key) returns a particular date stored in the map.
In this case you can simply use the java.util.Calendar to get the day of the month as an integer from your dates.
Date dt = Dates.get(key);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
Hope it helps!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm a bit baffled what format these timestamps are in. I was told the format to use is yyyy-MM-dd.HH:mm:ss but all of the timestamps appear like this 2017-01-01 00:08:57.231, 2017-01-01 07:43:36.348, or 2017-01-01 13:25:55.683. I'm not understanding why there are four sections to the time ?:Hour:Minute:Second in the actual data I have when the format I'm supposed to be using only has three time sections. Are these datetime timestamps not actually in the format of yyyy-MM-dd.HH:mm:ss?
No, your suspicion is correct, your example date-time strings are not in the format yyyy-MM-dd.HH:mm:ss. The dot between dd and HH must be a simple mistake, it should be a space since there is a space between date and time in the timestamp strings. Furthermore all of your example strings include milliseconds: in 00:08:57.231 you’ve got 57 seconds and 231 milliseconds, or if you like, 57.231 seconds, so the last section may also be referred to as fraction of second.
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
String timestampString = "2017-01-01 00:08:57.231";
LocalDateTime dateTime = LocalDateTime.parse(timestampString, formatter);
System.out.println(dateTime);
Output:
2017-01-01T00:08:57.231
For the nerdily curious: It is possible to parse the string, or more precisely most of it, with the format you had been given, only correcting the dot into a space:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestampString = "2017-01-01 00:08:57.231";
LocalDateTime dateTime = LocalDateTime.from(
formatter.parse(timestampString, new ParsePosition(0)));
In this case the result comes without the milliseconds:
2017-01-01T00:08:57
I see no reason why you should want this, though.
Avoid SimpleDateFormat
In a comment you gave a snippet that uses the SimpleDateFormat class. This class is not only long outdated, it is also notoriously troublesome. I see no reason why you should want to use it. Instead I am using java.time, the modern Java date and time API. In my experience it is so much nicer to work with.
Links
Oracle tutorial: Date Time explaining how to use java.time. You may especially want to study the section Parsing and Formatting.
These time stamps are in yyyy-MM-dd HH:mm:ss:ms format, last three digits are milliseconds.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to build a program that libraries can use. The user inputs the date they loaned the book, and it calculates that date + 5 days (when the book is due). Then checks if the current date is before or after the due date. Then says if it is late or not.
Use SimpleDateFormat to take the user input (as a String), and
convert it to a Date. Use Calendar for adding days to a given Date.
See also:
SimpleDateFormat
Date
Calendar
Use JodaTime instead and then you can call plusDays() on a DateTime object. There is also an isBefore() method as well. Here is a simple example:
DateTime loanDate = new DateTime();
DateTime dueDate = new DateTime().plusDays(8);
DateTime date = loanDate.plusDays(5);
System.out.println(date.isBefore(dueDate));
This returns true as the date is before the due date.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How to convert Object as timestamp to formatted date?
I have printed out timestamp(
1395500668
) that is in Object.
I want to format this and print it out like
yyyy-MM-dd H:m:s
Assuming you have a string that represents epoch time in seconds (as you have not told us what your Object actually is), first convert it to a long:
long epoch = Long.parseLong("1395500668");
You'll then need to convert it to milliseconds:
epoch *= 1000;
Then you can convert it to a java.util.Date using the Date constructor that takes millisecond epoch time:
Date date = new Date(epoch);
And finally you can format that Date as a string using standard formatting techniques.
First convert the timestamp value into Date and then format the date into your desired format using SimpleDateFormat
java.util.Date date = new java.util.Date(new Long(1395500668) * 1000);
String dateStr = new java.text.SimpleDateFormat("yyyy-MM-dd H:m:s").format(date);
System.out.println(dateStr);
It outputs:
2014-03-22 8:4:28
Convert it first into a Date first by casting the Object into a Timestamp and then using the getTime() method as shown in How to convert TimeStamp to Date in Java?
Then use a SimpleDateFormat to format the date as needed as shown in Change date format in a Java string
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
long beginupd = new GregorianCalendar(2014,3,14,10,55,25).getTime().getTime();
Date date = new Date();
long milli=date.getTime();
System.out.println(beginupd);
System.out.println(milli);
System.out.println(date);
output:
1397462125000
1394787327009
Fri Mar 14 10:55:27 EET 2014
What is my wrong? why is it not equal? difference onyl two second but output difference very large
OK!
0 for January and 11 for December. thank you David Wallace
If it is not already a Date, parse it into a Date. The date format is arbitrary as long as you can construct an appropriate SimpleDateFormat to represent it.
After you have a Date, you can use Date.getTime() to retrieve the millisecond value.
For the example you have shown, if you have a string:
String datestr = "2014-14-03 01:39:00";
Then the matching SimpleDateFormat would be:
DateFormat format = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss");
And conversion would be:
long millis = format.parse(datestr).getTime();
It's no problem to use Date for this, as the constructors and getTime() are still some of the few remaining non-deprecated components.
Edit: I see that you have edited your question to include the use of Date. The constructor you are using is deprecated, and is also not very flexible wrt. input (you have to have the date components already parsed to use it). A SimpleDateFormat provides a non-deprecated way to convert arbitrary strings to dates.
The reason this doesn't work is because the deprecated Date constructor that you're using expects year - 1900 as the first argument.
You should either use a SimpleDateFormat or a GregorianCalendar to do this conversion instead. Since there is already an excellent answer here, showing the use of SimpleDateFormat, here's how you use GregorianCalendar for 1:39am on 14 March 2014.
new GregorianCalendar(2014, 2, 14, 1, 39, 0).getTime().getTime();
Beware that the month uses 0 for January and 11 for December.
There is a nice article on the Date APIs that can be found here.
http://www.mkyong.com/java/java-time-elapsed-in-days-hours-minutes-seconds/
In order to convert to milliseconds, simply do some basic math.