get Date without time in java [duplicate] - java

This question already has answers here:
LocalDate to java.util.Date and vice versa simplest conversion? [duplicate]
(7 answers)
How do I get a Date without time in Java?
(23 answers)
Closed 3 years ago.
I want to get a Date without time, but always failed.
below is my codes:
long curLong = System.currentTimeMillis();
curLong = curLong - curLong % TimeUnit.DAYS.toMillis(1);
Date date = new Date(curLong);
System.out.println("date = " + date);
the output:
date = Mon Oct 28 08:00:00 CST 2019
anyone knows why? Thank you

It is not recommended to use java.util.Date anymore. It was called Date but doesn't necessarily hold only the date information but information about the time additionally.
Use this:
LocalDate today = LocalDate.now();
and print it as
System.out.println(today.format(DateTimeFormatter.ISO_DATE);
using the ISO date format. You can define your own formatting pattern using a
DateTimeFormatter.ofPattern("dd.MM.yyyy");
for example.

You can use java.time.LocalDate.now() to get just the date.
Anyway, your case doesn't work as you expect because you are doing nothing to remove the time from the date: you are just "repressing" it, that's why it's zero. If you want to continue this way you could always substring it (substring the Date.toString() of course I meant).
Hope I helped.

java.util.Date's javadoc states:
The class Date represents a specific instant in time, with millisecond precision.
Thats why you have date with time
If you want a date you can use : java.time.LocalDate.now() (Java 8+)

First of all, stop using the old java.util.Date. The new Java 8 date and time API has much better classes for all date and time operations.
The LocalDate class does exactly what you want.
The current date can be obtained by LocalDate.now().
It also has a lot of facilities to add and subtract days, months etc. and it takes into consideration all the calendar special cases for you.

Related

Get date 1 month ago as yyyy-mm-dd in kotlin [duplicate]

This question already has answers here:
How to reduce one month from current date and stored in date variable using java?
(8 answers)
Closed 1 year ago.
I need to get the date today, and the date one month ago in the format yyyy-mm-dd
To get the date today i have:
val todaysDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date()).toString()
Which works as i want:
2021-05-12
However i cannot figure out how to get the date for one month ago in the same format.
I found this function in another thread but it returns "Mon Apr 12 18:24:37 GMT+02:00 2021"
fun getDaysAgo(daysAgo: Int): Date {
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, -daysAgo)
return calendar.time
}
How can i get the date one month ago in the same format? Thanks.
Edit:
The solution for me was actually very simple using the getDaysAgo function
var daysAgo= SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(getDaysAgo(30)).toString()
However Ole's answer below is probably better and the recommended way. Did not work for me as it requires api level 26 (android) and im on 23.
LocalDate from java.time
Keep and process dates as LocalDate objects, not as strings.
Only when you need to give string output, format your LocalDate into a string in the appropriate format.
Like many in the comments I recommend that you use java.time, the modern Java date and time API, for your date work. In Java code, still keeping processing and formatting separate and trusting you to translate to Kotlin yourself:
public static LocalDate get1MonthAgo() {
return LocalDate.now(ZoneId.systemDefault()).minusMonths(1);
}
public static String formatToIso8601(LocalDate date) {
return date.toString();
}
Assuming that you need to output the date 1 month ago as a string, use the two methods like this:
LocalDate oneMonthAgo = get1MonthAgo();
String oneMonthAgoFormatted = formatToIso8601(oneMonthAgo);
System.out.println(oneMonthAgoFormatted);
When I ran this evening in my time zone, the output was:
2021-04-12
I am exploiting the facts that the format you asked for is ISO 8601, the international format, and that LocalDate (and also the other date-time classes of java.time) produce(s) ISO 8601 format from their toString methods. So we need to specify no formatter. Which is good because fiddling with a format pattern string is always error-prone.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601

Converting String to Date using SimpleDateFormat is returning random date [duplicate]

This question already has answers here:
String to Date Conversion mm/dd/yy to YYYY-MM-DD in java [duplicate]
(5 answers)
Parsing from String to Date throws Unparsable Date Error
(3 answers)
Closed 4 years ago.
I'm very confused by the following behaviour. I am returning 2 dates as Strings from a method:
getLastSupplierFlightResults()
I have added a screenshot showing the returned dates as "2018-06-20 00:00:00" and "2018-06-24 00:00:00" respectively and left the debug trace in to show the values.
I simply want to convert the dates into 20180620 format.
The methods:
.withStartDate()
.withEndDate()
...accept String values
What I don't understand is where the date "Wed Dec 06 00:00:00 GMT 2017" is coming from? This is the value that ends up being passed into the .withStart and .withEnd methods as 20171206.
As always, there is probably a simpler way of achieving my aims.
You are using the format pattern string yyyyMMdd. You are parsing the date-time string 2018-06-20 00:00:00.
2018 matches yyyy. MM means that month should be two chars, so -0 is taken for the month. And -0 or just 0 is taken to be the month before month 1 of 2018, that is, December 2017. Finally 6 is taken as the day of month. It should have been two chars too, but since there is only one digit, SimpleDateFormat settles with that. The remainder of the string is tacitly ignored.
Exactly the same thing happens when parsing the other string.
It’s the long outdated SimpleDateFormat class in a nutshell: In its attempts to be friendly and helpful it produces the most unpleasant and confusing surprises. Where you would have wished it would tell you something is wrong, it just pretends that everything is fine. It’s one of the main reasons that this class is considered troublesome, and why the replacement for the old classes came out with Java 8 more than 4 years ago. So just never use SimpleDateFormat again.
Instead look into java.time and its DateTimeFormatter.
Also don’t get date values as strings from your database. Depending on the datatype that the query returns get either a LocalDateTime or a LocalDate object. This will free you completely from parsing.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Seems like your pattern doesn't match stringDates you passing.
Try to use:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

How to transform in Java a Twitter Timestamp into a Date [duplicate]

This question already has answers here:
Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java [duplicate]
(2 answers)
Closed 4 years ago.
I need to transform a Twitter timestampe into a Java Date object,
here is an example of a value of a Timestampe: "2015-01-06T21:07:00Z"
Can you please give me sample of java code (standard Java) doing the job?
Thank you
I recommend you take advantage of the new Date/Time API introduced in Java 8, specifically Instant as follows:
Instant.parse("2015-01-06T21:07:00Z");
You can then perform a multitude of operations, but keep in mind that the object is immutable, so any changes to the instance (that aren't chained) must be stored in a separate variable.
Actually it is ISO 8601 format for UTC time zone.
It conforms with XML DateTime format as well.
So, to get actual java.util.Calendar or java.util.Date out of it you simply can use available in JDK
Calendar twitterCalendar = javax.xml.bind.DatatypeConverter.parseDateTime("2015-01-06T21:07:00Z");
Date twitterDate = javax.xml.bind.DatatypeConverter.parseDateTime("2015-01-06T21:07:00Z").getTime();
Just be aware: java.util.Date has no Time Zone information in it. Your string is in UTC, so if you try to print value of twitterDate you will see Date/Time in TimeZone of your computer/server. Still actual value of twitterDate stays the same
millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).

Java Date changing format [duplicate]

This question already has answers here:
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
(8 answers)
Closed 5 years ago.
I am trying to change the format of Date objects, I am trying to do it in this way:
for(Date date : dates){
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String formatterDate = formatter.format(date);
Date d = formatter.parse(formatter.format(date));
}
But this does not have any effect on the d object, it is still with the old format, can't really understand why it is like that.
Please try to keep two concepts apart: your data and the presentation of the data to your user (or formatting for other purposes like inclusion in JSON). An int holding the value 7 can be presented as (formatted into) 7, 07, 007 or +7 while still just holding the same value without any formatting information — the formatting lies outside the int. Just the same, a Date holds a point in time, it can be presented as (formatted into) “June 1st 2017, 12:46:01.169”, “2017/06/01” or “1 Jun 2017” while still just holding the same value without any formatting information — the formatting lies outside the Date.
Depending on your requirements, one option is you store your date as a Date (or better, an instance of one of the modern date and time classes like LocalDate) and keep a formatter around so you can format it every time you need to show it to the user. If this won’t work and you need to store the date in a specific format, then store it as a String.
Java 8 (7, 6) date and time API
Now I have been ranting about using the newer Java date and time classes in the comments, so it might be unfair not to show you that they work. The question tries to format as yyyy-MM-dd, which we may do with the following piece of code.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd");
for (LocalDate date : localDates) {
String formatterDate = date.format(dateFormatter);
System.out.println(formatterDate);
}
In one run I got
2017/05/23
2017/06/01
Should your objects in the list have other types than LocalDate, most other newer date and time types can be formatted in exactly the same way using the same DateTimeFormatter. Instant is a little special in this respect because it doesn’t contain a date, but you may do for example myInstant.atZone(ZoneId.of("Europe/Oslo")).format(dateFormatter) to obtain the date it was/will be in Oslo’s time zone at that instant.
The modern classes were introduced in Java 8 and are enhanced a bit in Java 9. They have been backported to Java 6 and 7 in the ThreeTen Backport with a special edition for Android, ThreeTenABP. So I really see no reason why you should not prefer to use them in your own code.
Try this one.
String formattedDate = null;
SimpleDateFormat sdf = new SimpleDateFormat(format you want);
formattedDate = sdf.format( the date you want to format );
return formattedDate;
some not best solution, but it works: this method will convert Date object to String of any pattern you need
public static void format(Date date){
String pattern = "MMM d yyyy";
LocalDateTime localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
String result = formatter.format(localDate);
// new Date() -> Jun 1 2017
}
SimpleDateFormat is useful while converting Date to String or vice-versa. java.util.Date format will always remain same. If you want to display it in standalone application then use date.getxxx() methods and choose your design.

Convert java.time.LocalDateTime SE 8 to timestamp [duplicate]

This question already has answers here:
Convert LocalDate to LocalDateTime or java.sql.Timestamp
(7 answers)
Closed 4 years ago.
How do you convert a Localdatetime to timestamp? I want to use the new SE 8 date api because it is better than the util date and calendar. I plan to use localdatetime throughout my program and then place that date into a mysql database. I have looked for an answer but there doesn't seem to be very many questions and answers for java.time. This is a little of the code that I am testing. This is as far as I got.
LocalDateTime c = LocalDateTime.now();
java.sql.Timestamp javaSqlDate = new java.sql.Timestamp(c.getLong());
I think I need to convert it into a long first, but I don't know how. The api allows for converting individual elements like month and day, but not for the whole date. Since I'm already here, how do you convert back from timestamp? Should I just use jodatime?
I tried this:
LocalDateTime c = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
System.out.println("this:" + c);
java.sql.Timestamp javaSqlDate = new java.sql.Timestamp(c.atZone(zoneId).toEpochSecond());
pst.setTimestamp(2, javaSqlDate);
This only saves the date around 1970. The system.print prints the current date correctly. I want it to save the current date.
LocalDateTime l = LocalDateTime.now();
Timestamp t = Timestamp.valueOf(l);
Source: https://coderanch.com/t/651936/databases/Convert-java-time-LocalDateTime-SE
First of all, you should decide if you really want to use LocalDateTime.
Below are some explanations about the difference, taken from here:
<...> LocalDateTime is not a point on the time line as Instant is, LocalDateTime is just a date and time as a person would write on a note. Consider the following example: two persons which were born at 11am, July the 2nd 2013. The first was born in the UK while the second in California. If we ask any of them for their birth date it will look that they were born on the same time (this is the LocalDateTime) but if we align the dates on the timeline (using Instant) we will find out that the one born in California is few hours younger than the one born in the UK (NB: to create the appropriate Instant we have to convert the time to UTC, this is where the difference lays).<...>
In order to get long from Instant you could use getEpochSecond() method.
In order to get long from LocalDateTime you should provide a timezone.

Categories

Resources