Use SimpleDateFormat instead:
private String toDate(long timestamp) {
Date date = new Date(timestamp * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
Updated: Java 8 solution:
private String toDate(long timestamp) {
LocalDate date = Instant.ofEpochMilli(timestamp * 1000).atZone(ZoneId.systemDefault()).toLocalDate();
return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
You can use this code to get the required results
protected Timestamp timestamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
protected String today_Date=timestamp.toString().split(" ")[0];
Don't use the ancient java.util.Date object. Use the new Java 8 Time API, i.e. parse the 2019-07-03 12:14:11 date string to a LocalDateTime object, then call toLocalDate() to get the date-only LocalDate value, which would then be the key in your map (Map<LocalDate, List<Integer>>).
Your code would then be:
map.computeIfAbsent(invoiceHeader.getInvoice_Date().toLocalDate(), x -> new ArrayList<>())
.add(invoiceId);
If getInvoice_Date() returns a java.util.Date, then you can get the LocalDate value like this:
Instant invoiceInstant = invoiceHeader.getInvoice_Date().toInstant();
LocalDateTime invoiceDateTime = LocalDateTime.ofInstant(invoiceInstant, ZoneId.systemDefault());
LocalDate invoiceDate = invoiceDateTime.toLocalDate();
Combining the code above gives you:
map.computeIfAbsent(LocalDateTime.ofInstant(invoiceHeader.getInvoice_Date().toInstant(),
ZoneId.systemDefault()).toLocalDate(),
x -> new ArrayList<>())
.add(invoiceId);
Here you add/get date + time as key in the map. It will not work because you have to add the date without time if you want to be able to have the same key for same date but with different time.
Note that you should use LocalDateTime instead of Date that is a better designed API and that has the advantage to be immutable, which is advised for map keys.
With a few change you could do that :
LocalDate date = invoiceHeader.getInvoice_Date().toLocalDate();
if(map.containsKey(date)){
map.get(date).add(invoiceId);
}
else{
List<Integer> invoicesList = new ArrayList<>();
invoicesList.add(invoiceId);
map.put(date,invoicesList);
}
With Map.computeIfAbsent() that provides a fluent API : you could simplify the whole logic such as :
LocalDate date = invoiceHeader.getInvoice_Date().toLocalDate();
map.computeIfAbsent(date, k-> new ArrayList<>()).add(invoiceId);
Just make a new Date object with the stamp's getTime() value as a parameter.
Here's an example (I use an example timestamp of the current time):
Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
System.out.println(date);
// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );
// Date to timestamp
long timestamp = d.getTime();
//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();
Use java.text.SimpleDateFormat and java.util.TimeZone
Which timezone the date string is in? Replace the below UTC timezone with that timezone
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2014-02-15 05:18:08");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
sdf2.setTimeZone(TimeZone.getTimeZone("IST"));
String dateStr = sdf2.format(date); // Output: 15-02-2014 10:48:08 AM
Note: In which format the hour is in (24 hour/ 12 hour) in your input string? The above example assumes that it is in 24 hour format because there in no AM/PM info in the input string.
If the input string is also in 12 hour format then your input string should mention AM/PM info also such as 2014-02-15 05:18:08 PM. In that case, modify the sdf to new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a")
======================== Edited: =====================
To answer your next question in comment "How to extract date and time separately"...
SimpleDateFormat sdfDate = new SimpleDateFormat("dd-MM-yyyy");
sdfDate.setTimeZone(java.util.TimeZone.getTimeZone("IST"));
SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss a");
sdfTime.setTimeZone(java.util.TimeZone.getTimeZone("IST"));
String dateStr = sdfDate.format(date);
String timeStr = sdfTime.format(date);
The accepted answer by Yatendra Goel is correct.
Joda-Time
For fun, here's the same kind of code using the Joda-Time 2.3 library.
Note that Joda-Time is now in maintenance mode. The team advises migration to java.time. See my other Answer for java.time code.
FYI… India is five and a half hours ahead of UTC/GMT. Hence the thirty minute difference in the outputs below.
String input = "2014-02-15 05:18:08";
input = input.replace( " ", "T" ); // Replace space in middle with a "T" to get ISO 8601 format.
// Parse input as DateTime in UTC/GMT.
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
// Adjust to India time.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTime = dateTimeUtc.withZone( timeZone );
// Using "en" for English here because (a) it is irrelevant in our case, and (b) I don't know any Indian language codes.
java.util.Locale localeIndiaEnglish = new Locale( "en", "IN" ); // ( language code, country code );
DateTimeFormatter formatter = DateTimeFormat.forStyle( "SS" ).withLocale( localeIndiaEnglish ).withZone( timeZone );
String output = formatter.print( dateTime );
DateTimeFormatter formatterDateOnly = DateTimeFormat.forPattern( "dd-MM-yyyy" ).withLocale( localeIndiaEnglish ).withZone( timeZone );
DateTimeFormatter formatterTimeOnly = DateTimeFormat.forPattern( "hh:mm:ss a" ).withLocale( localeIndiaEnglish ).withZone( timeZone );
String dateOnly = formatterDateOnly.print( dateTime );
String timeOnly = formatterTimeOnly.print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTime: " + dateTime );
System.out.println( "output: " + output );
System.out.println( "dateOnly: " + dateOnly );
System.out.println( "timeOnly: " + timeOnly );
When run…
input: 2014-02-15T05:18:08
dateTimeUtc: 2014-02-15T05:18:08.000Z
dateTime: 2014-02-15T10:48:08.000+05:30
output: 15/2/14 10:48 AM
dateOnly: 15-02-2014
timeOnly: 10:48:08 AM
Do you absolutely have to use java.util.Date? I would thoroughly recommend that you use Joda Time or the java.time package from Java 8 instead. In particular, while Date and Calendar always represent a particular instant in time, with no such concept as "just a date", Joda Time does have a type representing this (LocalDate). Your code will be much clearer if you're able to use types which represent what you're actually trying to do.
There are many, many other reasons to use Joda Time or java.time instead of the built-in java.util types - they're generally far better APIs. You can always convert to/from a java.util.Date at the boundaries of your own code if you need to, e.g. for database interaction.
Here is what I used to get today's date with time set to 00:00:00:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date today = new Date();
Date todayWithZeroTime = formatter.parse(formatter.format(today));
Use SimpleDateFormat:
java.util.Date date = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(date));
If you have the date as a String, you can parse it to a java.util.Date in a step before:
SimpleDateFormat sdf = new SimpleDateFormat("YOUR_DATE_PATTERN");
Date date = sdf.parse(string);
Use patterns according to https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
If I have understood the question correctly 2014-09-01 10:00:00.000 is in a string and 10:00:00 has to be extracted from that. Given below is my solution.
- First split the string with space as the delimiter.
- Then from that take the second part of the string.
- After that split the string again using
.as the delimiter and take the first sting from that.
The above things are done using the line.
str.split("\\s")[1].split("\\.")[0];
COMPLETE CODE
String str = new String("2014-09-01 10:00:00.000");
String time = str.split("\\s")[1].split("\\.")[0];
System.out.print(time);
OUTPUT
10:00:00
For more details check the links given below:
- String.split().
- Patterns
// Get the current date and time
LocalDateTime now = LocalDateTime.now();
// Define the format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// Format the current date and time
String formattedNow = now.format(formatter);
// Print the formatted date and time
System.out.println("Current Timestamp:" + formattedNow);
Legacy Answer
Replace
new Timestamp();
with
new java.util.Date()
because there is no default constructor for Timestamp, or you can do it with the method:
new Timestamp(System.currentTimeMillis());
Use java.util.Date class instead of Timestamp.
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
This will get you the current date in the format specified.
All you need to do is change the string within the java.text.SimpleDateFormat constructor to:
"MM-dd-yyyy HH:mm:ss".
Just use the appropriate letters to build the above string to match your input date.
tl;dr
java.sql.Timestamp
.valueOf( // Class-method parses SQL-style formatted date-time strings.
"2007-11-11 12:13:14"
) // Returns a `Timestamp` object.
.toInstant() // Converts from terrible legacy classes to modern *java.time* class.
java.sql.Timestamp.valueOf parses SQL format
If you can use the full four digits for the year, your input string of 2007-11-11 12:13:14 would be in standard SQL format assuming this value is meant to be in UTC time zone.
The java.sql.Timestamp class has a valueOf method to directly parse such strings.
String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;
java.time
In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString method. In contrast, the java.time classes by default use the standard ISO 8601 formats.
System.out.println( "Output: " + ts.toInstant().toString() );
This may be helpful.
long dateTimeStamp = 1487269800;
Timestamp stamp = new Timestamp(dateTimeStamp*1000);
Date changeDate = new Date(stamp.getTime());
Output:
Date :Fri Feb 17 00:00:00 IST 2017
Try this -
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
String valueFromDB = "2012-12-31 00:00:00.0";
Date d1 = sdf1.parse(valueFromDB);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String dateWithoutTime = sdf.format(d1);
System.out.println("sdf.format(d) " + dateWithoutTime);
For 1280512800, multiply by 1000, since java is expecting milliseconds:
java.util.Date time=new java.util.Date((long)timeStamp*1000);
If you already had milliseconds, then just new java.util.Date((long)timeStamp);
From the documentation:
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
java.time.Instant.ofEpochSecond
Java 8 introduced a new API for working with dates and times: the java.time package.
With java.time you can parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. The result is an Instant.
Instant instant = Instant.ofEpochSecond( timeStamp );
If you need a java.util.Date to interoperate with old code not yet updated for java.time, convert. Call new conversion methods added to the old classes.
Date date = Date.from( instant );