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

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

Related

JDatePicker Date difference in Java

I created a GUI with several JDatePicker objects. Now I’m trying to compute the difference between two JDatePicker dates. But I don’t have a clue how to start. Can anyone help me please?
The date in the JDatePicker is a String object. I guess I need to convert the String into a date object and then convert it to a long object. Am I on the right path?
Locale.setDefault(Locale.UK); // So that other readers can run the example; don’t include in your production code
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
String dateString1FromJDatePicker = "24 November 2019";
String dateString2FromJDatePicker = "29 February 2020";
LocalDate from = LocalDate.parse(dateString1FromJDatePicker, dateFormatter);
LocalDate to = LocalDate.parse(dateString2FromJDatePicker, dateFormatter);
long difference = ChronoUnit.DAYS.between(from, to);
System.out.println(difference);
Output from this example piece of code is:
97
It takes two steps:
Parse each date string into a LocalDate.
Use ChronoUnit.DAYS.between() for obtaining the difference in days between the two dates.
As a possibly better alternative you may look for a date picker component that has integration with java.time, the modern Java date and time API, so that you don’t need to parse the string yourself.
Links
SourceForge JDatePicker.
Oracle tutorial: Date Time explaining how to use java.time.

Remove the day name from date and set it as only 'yyyy-MM-dd HH:mm:ss' [duplicate]

This question already has answers here:
Java Date changing format [duplicate]
(4 answers)
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
(8 answers)
Closed 5 years ago.
I'm trying to get the current day's date at 6 am in the format yyyy-MM-dd HH:mm:ss, but it shows as : Wed Dec 20 06:00:00 CST 2017
This is my code:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 06:00:00");
Date date0 = new Date();
String x = dateFormat.format(date0);
try{
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = formatter.parse(x);
}
catch (Exception e){}
java.util.Date is a container for the number of milliseconds since the Unix Epoch, it doesn't not maintain any kind of internal formatting concept, instead, when you print it, it use Date#toString which generally uses the current Locale to provide a human readable representation of the value.
While I'm sure you could continue to mess about with Date to make this work, a much simpler approach would be to take advantage of the newer Date/Time API, something like...
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.withHour(6).withMinute(0).withSecond(0).withNano(0);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(then);
System.out.println(formatted);
Which, for me, prints out 2017-12-21 06:00:00
TL;DR
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
LocalDate date0 = LocalDate.now(ZoneId.of("America/Winnipeg"));
String at6Am = date0.atTime(LocalTime.of(6, 0)).format(formatter);
System.out.println(at6Am);
Running just now this printed
2017-12-21 06:00:00
Details
The classes that you use, Date and SimpleDateFormat, have been around since Java 1.0, some 20 years. They have proved to be poorly designed and cumbersome to use. Maybe for that reason too, much has been written about them, and from searching the web you could easily get the impression that these are the classes you should use. On the contrary, they are the classes you should avoid. Their replacement came out with Java 8, it will soon be 4 years ago.
Formatters are for formatting and parsing. You shouldn’t use a formatter, even less two formatters, for changing the time-of-day to 6 AM.
It is never the same date everywhere on the globe. So getting today’s date is an operation that depends on a time zone. I have made the time zone explicit in my code so the reader will also be aware of this fact. Please substitute your desired time zone if it didn’t happen to be America/Winnipeg.
You are modifying existing software. If you got an old-fashioned Date object from it, first convert it to the modern Instant type, then use the modern API for further operations. For example:
Date date0 = getOldfashionedDateFromLegacyApi();
String at6Am = date0.toInstant()
.atZone(ZoneId.of("America/Winnipeg"))
.with(LocalTime.of(6, 0))
.format(formatter);
What went wrong in your code?
I don’t think there’s anything really wrong with the code in your question. You wanted your date-time formatted as 2017-12-20 06:00:00, and you got that in the string x in the third code line. Be happy with that and leave out the remainder of the code.
There is no such thing as imposing the format on the date-time objects, (no matter if we talk the outdated or the modern API). Formatting a date-time means converting it to a String in the desired format.
After parsing, you need to format it as follows: formatter.format(date). So modify your code as follows:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 06:00:00");
Date date0 = new Date();
String x = dateFormat.format(date0);
try{
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = formatter.format(formatter.parse(x));
}
catch (Exception e){}

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.

Subtracting and comparing Dates

I have found some similar Que's on SO but had not find the solution.
I have today's Date as following: (Let's say this as Date1 and it's value as 2012-06-22)
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd");
Date start = cal.getTime();
String currentDate=dateformatter.format(start);
I'm retrieving 4 values from the user:
Particular Date (Assume 5)
Particular Month (Assume 1)
Particular Year (Assume 2012)
No. of days (Assume 7)
So this date, say Date2 becomes 2012-01-05 (yyyy-MM-dd) along with No. of days set to 7.
I want to compare Date 1 and Date 2-No. of days.
I know that by using following snippet, particular no. of days can be subtracted from a calender instance.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -7);
But since I'm having Date2 in form of String, I'm not able to follow this approach.
Any help appreciated.
Edit:
From your suggestions, I'll be able to convert String to Date by using parse method of SimpleDateFormat.
Now I've 2 Date Objects.
How do I find Difference between them in terms of days, months, and years?
How to Subtract particular no. of days, say 7, from a particular date, say 2012-01-05?
java.time
The question and the accepted answer have used the java.util Date-Time API and their parsing/formatting API, SimpleDateFormat which was appropriate thing to do using the standard library in 2012. In March 2014, Java 8 introduced the modern Date-Time API which supplanted the legacy API and since then it is highly recommended to use the modern Date-Time API.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Requirements copied from your question:
From your suggestions, I'll be able to convert String to Date by using
parse method of SimpleDateFormat.
Now I've 2 Date Objects.
How do I find Difference between them in terms of days, months, and
years?
How to Subtract particular no. of days, say 7, from a
particular date, say 2012-01-05?
Solution using java.time, the modern Date-Time API:
With java.time, you can parse your date string into a LocalDate and then find the Period between this date and the current date (which you obtain with LocalDate.now()). You can also subtract days, months, and years using methods like minusXxx/minus. You have similar methods (plusXxx/plus) for adding these units. Check the documentation of LocalDate to learn more about it.
Note: java.time API is based on ISO 8601 and therefore you do not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format (e.g. your date-time string, 2012-06-22).
Demo:
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
class Main {
public static void main(String[] args) {
LocalDate then = LocalDate.parse("2012-06-22");
LocalDate now = LocalDate.now();
Period period = Period.between(then, now);
System.out.println(period);
System.out.printf("%d years %d months %d days%n",
period.getYears(), period.getMonths(), period.getDays());
// Examples of subtracting date units
LocalDate sevenDaysAgo = now.minusDays(7);
System.out.println(sevenDaysAgo);
// Alternatively
sevenDaysAgo = now.minus(7, ChronoUnit.DAYS);
System.out.println(sevenDaysAgo);
}
}
Output from a sample run:
P10Y6M27D
10 years 6 months 27 days
2023-01-11
2023-01-11
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
use SimpleDateFormat to convert String (representing date) to Date
For example :
Date parsedDate = new SimpleDateFormat("yyyy-MM-dd").parse("2012-01-05");
If you can possibly use Joda Time instead of Date/Calendar, do so. It'll make your life easier.
If not, it sounds like you don't want to format the current date - instead, you want to parse Date2 from the user:
Date date2 = dateFormatter.parse(text);
Then you can either create a calendar and subtract a particular number of days, or (if you're talking about elapsed time - you need to think about your behaviour around DST transitions and time zones here) you could just subtract 7 * 24 * 60 * 60 * 1000 milliseconds from date2.getTime().
Fundamentally, you should convert out of a string format as earlier as possible, and only convert to a string format when you really need to - certainly not for comparisons. The natural representation of this data is as a Date or Calendar (assuming you're sticking with the JDK), so work towards getting your data into that representation.
You have several genuine "business" questions to think about though:
Do you want to compare the current date with the date the user's given, or the current date and time with the date the user's given?
What time zone do you want to use for the user's input?
Are you thinking about elapsed days or "logical" days? Because 7 * 24 hours earlier than 1.30am may be 2.30am or vice versa, due to DST transitions
You should answer all those questions before you try to implement your code, as it will affect the representation you use. Also, write unit tests for everything you can think of before you start the implementation.
From my understanding you have two dates now and you want to subtract a particular number of days from date.
First you can use SimpleDateFormat to convert a date to string and string to date
Now to subtract days say 7. you can get time of the date and subtract 7*24*60*60*1000 from it
long daybeforeLong = 7 * 24 * 60 * 60 * 1000;
try {
Date todayDate = new Date();
long nowLong = todayDate.getTime();
Date beforeDate = new Date((nowLong - daybeforeLong));
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think you can make use of Comparator provided by java will do work of comparing and sorting the dates too.
here is the link
hope you get what you was looking for..

Categories

Resources