I am new to kotlin. And I got a problem.
I have this code:
val sdf = SimpleDateFormat("dd.MM.yyyy")
val currentDate = sdf.format(Date())
println(currentDate)
val stringDate = "12.03.2015"
val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH)
val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli()
println(millisecondsSinceEpoch)
val time = currentDate - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
But on the line:
val time = currentDate - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
I get the error:
java.lang.IllegalArgumentException: Cannot format given Object as a Date
Please help me how you can fix this. I need to subtract the current date from the date that is in string.
UPDATE:
How to subtract one date from another correctly and get the difference in days?
I suggest you switch from the outdated java.util date/time API to the modern date/time API. Given below is the Java code for your requirement and I hope you should be able to convert the same into Kotlin. However, if you face any issue, I can convert the same into Kotlin code for you.
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Define format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH);
// Given date-time
ZonedDateTime givenDateTime = LocalDateTime.of(LocalDate.parse("12.03.2015", formatter), LocalTime.of(0, 0))
.atZone(ZoneId.of("Etc/UTC"));
// Now
ZonedDateTime zdtNow = ZonedDateTime.now(ZoneId.of("Etc/UTC"));
// Period between the two dates
Period period = Period.between(givenDateTime.toLocalDate(), zdtNow.toLocalDate());
// Given date-time with current year, month and day
ZonedDateTime adjusted = givenDateTime.with(LocalDate.now(ZoneId.of("Etc/UTC")));
// Duration between the two times
Duration duration = Duration.between(adjusted, zdtNow);
// Display each part of the period and duration
System.out.printf("%d years %d month %d days %d hours %d minutes %d seconds %d nanoseconds", period.getYears(),
period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart(), duration.toNanosPart());
}
}
Output:
5 years 4 month 7 days 19 hours 30 minutes 37 seconds 507058000 nanoseconds
Using OffsetDateTime:
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Define format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH);
// Given date-time
OffsetDateTime givenDateTime = LocalDateTime.of(LocalDate.parse("12.03.2015", formatter), LocalTime.of(0, 0))
.atOffset(ZoneOffset.UTC);
// Now
OffsetDateTime odtNow = OffsetDateTime.now(ZoneOffset.UTC);
// Period between the two dates
Period period = Period.between(givenDateTime.toLocalDate(), odtNow.toLocalDate());
// Given date-time with current year, month and day
OffsetDateTime adjusted = givenDateTime.with(LocalDate.now(ZoneOffset.UTC));
// Duration between the two times
Duration duration = Duration.between(adjusted, odtNow);
// Display each part of the period and duration
System.out.printf("%d years %d month %d days %d hours %d minutes %d seconds %d nanoseconds", period.getYears(),
period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart(), duration.toNanosPart());
}
}
Following is the corrected version of your initial program. However as others pointed out it is advisable to use new java Time API.
There is nice article highlighting problem with old Java Date and Calendar API
https://programminghints.com/2017/05/still-using-java-util-date-dont/
import java.util.Date
import java.util.Locale
import java.time.Instant
import java.time.LocalDateTime
import java.time.LocalDate
import java.time.ZoneOffset
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
val sdf = SimpleDateFormat("dd.MM.yyyy")
val currentDate = Date()
val currentFormattedDate = sdf.format(currentDate)
println(currentFormattedDate)
val now = currentDate.getTime();
val stringDate = "12.03.2015"
val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH)
val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli()
println(millisecondsSinceEpoch)
val time = now - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
}
Thanks everyone. But I decided to do this. And it seems like everything works)
fun daysString(dataend: String):String{
val dateFormat = SimpleDateFormat("dd.MM.yyyy")
val endDate = dateFormat.parse(dataend)
val currentDate = Date()
val time = endDate.time - currentDate.time
val days = time / 1000 / 3600 / 24
val strtoday = days.toString()
return strtoday
}
Now in the code I am using:
val data_end = "10.10.2020"
daysString(data_end)
and I get strtoday
Get your required Date and then can do this:
val sdf = SimpleDateFormat("dd/MM/yyyy",Locale.ENGLISH)
val theDate = sdf.parse(selectedDate)
val selectedDate = theDate!!.time/86400000 //.time gives milliseconds
val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))
val currentDate = currentDate!!.time/86400000 //86400000 milliseconds in a day
val diff = currentDate - selectedDate
println(diffInMinutes.toString()) //set it to any view or use as needed
Related
I want to add offset GMT +05:30 to Time but I don't know how to do that
String offset = data ['utc_offset'].substring(1,);
ntime =ntime.add(Duration(hours:int.parse(offset)));
Since there is " : " in the middle of 05:30 I can't add the exact value..
PS: I'm using http://worldtimeapi.org JSON API
You can parse the offset time by using a RegExp. I have used named groups in my example since I finds it more simple to understand what each part of the regexp are extracting:
import 'dart:io';
void main() {
const offset = '+01:00';
final regexp =
RegExp(r'^(?<plusMinus>[+-]?)(?<hours>[\d]+):(?<minutes>[\d]+)');
final match = regexp.firstMatch(offset);
print(match.namedGroup('plusMinus'));
print(match.namedGroup('hours'));
print(match.namedGroup('minutes'));
final offsetDuration = Duration(
hours: int.parse(match.namedGroup('hours')),
minutes: int.parse(match.namedGroup('minutes')));
DateTime time;
if (match.namedGroup('plusMinus') == '+') {
time = DateTime.now().add(offsetDuration);
} else if (match.namedGroup('plusMinus') == '-') {
time = DateTime.now().subtract(offsetDuration);
} else {
time = DateTime.now();
}
print(time);
}
This question already has answers here:
How to set 24-hours format for date on java?
(10 answers)
Closed 3 years ago.
I am trying to convert time zones with given time in my properties file.
package test1;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class TimeZoneConversion {
private static final String DATE_FORMAT = "yyyy-MM-dd-hh-mm-ss";
public static void main(String[] args) {
String ds = "2019-03-18 13-14-48";
LocalDateTime ldt = LocalDateTime.parse(ds, DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println("ldt : "+ldt);
ZoneId singaporeZoneId = ZoneId.of("Asia/Singapore");
System.out.println("TimeZone : " + singaporeZoneId);
//LocalDateTime + ZoneId = ZonedDateTime
ZonedDateTime asiaZonedDateTime = ldt.atZone(singaporeZoneId);
System.out.println("Date (Singapore) : " + asiaZonedDateTime);
ZoneId newYokZoneId = ZoneId.of("America/New_York");
System.out.println("TimeZone : " + newYokZoneId);
ZonedDateTime nyDateTime = asiaZonedDateTime.withZoneSameInstant(newYokZoneId);
System.out.println("Date (New York) : " + nyDateTime);
DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT);
System.out.println("\n---DateTimeFormatter---");
System.out.println("Date (Singapore) : " + format.format(asiaZonedDateTime));
System.out.println("Date (New York) : " + format.format(nyDateTime));
}
}
SO I am getting error :
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-03-18 13-14-48' could not be parsed: Invalid value for ClockHourOfAmPm (valid values 1 - 12): 13
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at test1.FirstClass.main(FirstClass.java:20)
I do not have AM/PM value in the date time that I getting from properties file. This value is stored in String ds. in the above code I have hardcoded it. How does it work? How to make it work with the time date format which I have given?
You should change the DATE_FORMAT to:
private static final String DATE_FORMAT = "yyyy-MM-dd HH-mm-ss";
If you refer the DateTimeFormatter docs you see the description as follows:
H hour-of-day (0-23)
In your case you are supplying the hour as the hour-of-day (HH) instead of in clock-hour-of-am-pm (hh a) format from your properties file. And as 13 ( > 12) is not an acceptable value for clock-hour-of-am-pm without the AM/PM you are getting an exception.
If you want it in clock-hour-of-am-pm you need to change the format to:
private static final String DATE_FORMAT = "yyyy-MM-dd hh-mm-ss a";
And also add the AM/PM information in the date string:
String ds = "2019-03-18 12-14-48 AM";
I am trying to parse date format '2017-12-18T20:41:06.136Z' into "2017-12-18'T'00:00:00"
Date date = new Date();
def dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
dateformat.setTimeZone(TimeZone.getTimeZone(TimeZoneCode));
def currentDate = dateformat.format(date)
log.info "Current Date : " + currentDate
date1 = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00").parse(currentDate)
log.info "Current Date : " + date1
Error displayed :
java.text.ParseException: Unparseable date: "2017-12-18T20:46:06:234Z" error at line: 16
This line gives error :
date1 = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00").parse(currentDate)
Running Groovy on Java 8 gives you access to the much better Date/Time classes... You can just do:
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
String result = ZonedDateTime.parse("2017-12-18T20:41:06.136Z")
.truncatedTo(ChronoUnit.DAYS)
.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
In order to avoid the mentioned error, use below statement Date.parse(..):
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def dateString = "2017-12-18T20:41:06.136Z"
def date = Date.parse(dateFormat, dateString)
You should be able to achieve what you are trying to using below script.
//Change timezone if needed
def tz = 'IST'
TimeZone.setDefault(TimeZone.getTimeZone(tz))
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def dateString = "2017-12-18T20:41:06.136Z"
Calendar calendar = Calendar.getInstance()
calendar.with {
time = Date.parse(dateFormat,dateString)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
log.info calendar.time.format(dateFormat)
You can quickly try the same online demo
if you need to parse only part of date, use the following syntax:
Date.parse("yyyy-MM-dd'T'HH:mm:ss",'2017-12-18T16:05:58bla-bla')
Trying to add 1 day to the simple date format.
import java.text.SimpleDateFormat
Date date = new Date();
def dateformat = new SimpleDateFormat("YYYY-MM-dd")
def currentDate = dateformat.format(date)
log.info "Current Date : " + currentDate
Date date1 = (Date)dateformat.parse(currentDate);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
log info c1.add(Calendar.Date,1);
Error occurred in line :
"log info c1.add(Calendar.Date,1);"
groovy.lang.MissingPropertyException:No such property: info for class: Script16 error at line: 10
Note : The current date should be any date in future and i want to increment by 1 day.
You can use TimeCategory to add the day as shown below:
use(groovy.time.TimeCategory) {
def tomorrow = new Date() + 1.day
log.info tomorrow.format('yyyy-MM-dd')
}
EDIT: based on OP comments
Here is another away which is to add method dynamically, say nextDay() to Date class.
//Define the date format expected
def dateFormat = 'yyyy-MM-dd'
Date.metaClass.nextDay = {
use(groovy.time.TimeCategory) {
def nDay = delegate + 1.day
nDay.format(dateFormat)
}
}
//For any date
def dateString = '2017-12-14'
def date = Date.parse(dateFormat, dateString)
log.info date.nextDay()
//For current date
def date2 = new Date()
log.info date2.nextDay()
You may quickly the same online demo
Well, the error you provide clearly tells you, that you have a syntax error. It says that there is no property info.
This is because you write
log info c1.add(Calendar.Date,1);
instead of
log.info c1.add(Calendar.Date,1);
If you would have used the correct syntax, it would complain that Calendar has no property Date.
So instead of
c1.add(Calendar.Date, 1)
you meant
c1.add(Calendar.DAY_OF_MONTH, 1)
But in Groovy you can even make it easier, using
c1 = c1.next()
Is it possible to parse a date and extract the week of month using Joda-Time. I know it is possible to do it for the week of year but I cannot find how/if it is possible to extract the week of month.
Example: 2014-06_03 where 03 is the third week of this month
DateTime dt = new DateTime();
String yearMonthWeekOfMonth = dt.toString("<PATTERN for the week of month>");
I have tried the pattern "yyyyMMW" but it is not accepted.
Current joda-time version doesn't support week of month, so you should use some workaround.
1) For example, you can use next method:
static DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM_'%d'");
static String printDate(DateTime date)
{
final String baseFormat = FORMATTER.print(date); // 2014-06_%d
final int weekOfMonth = date.getDayOfMonth() % 7;
return String.format(baseFormat, weekOfMonth);
}
Usage:
DateTime dt = new DateTime();
String dateAsString = printDate(dt);
2) You can use Java 8, because Java's API supports week of month field.
java.time.LocalDateTime date = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM_W");
System.out.println(formatter.format(date));
This option in Joda is probably nicer:
Weeks.weeksBetween(date, date.withDayOfMonth(1)).getWeeks() + 1
For the case you don't like calculations so much:
DateTime date = new DateTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date.toDate());
int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
If the start day of week is Monday then you can use it:
public int getWeekOfMonth(DateTime date){
DateTime.Property dayOfWeeks = date.dayOfWeek();
return (int) (Math.ceil((date.dayOfMonth().get() - dayOfWeeks.get()) / 7.0)) + 1;
}