I need to display tomorrow's date only , l have this code and his working fine without problem . and he is give the current date for today. l want change this code to get the date for tomorrow but l dont know how !
private fun date24hours(s: String): String? {
try {
val sdf = SimpleDateFormat("EE, MMM d, yyy")
val netDate = Date(s.toLong() * 1000)
return sdf.format(netDate)
} catch (e: Exception) {
return e.toString()
It is possible to use Date for this, but Java 8 LocalDate is a lot easier to work with:
// Set up our formatter with a custom pattern
val formatter = DateTimeFormatter.ofPattern("EE, MMM d, yyy")
// Parse our string with our custom formatter
var parsedDate = LocalDate.parse(s, formatter)
// Simply plus 1 day to make it tomorrows date
parsedDate = parsedDate.plusDays(1)
I might be late to the party, but this is what I found works for me
const val DATE_PATTERN = "MM/dd/yyyy"
internal fun getDateTomorrow(): String {
val tomorrow = LocalDate.now().plusDays(1)
return tomorrow.toString(DATE_PATTERN)
}
With LocalDate and DateTimeFormatter:
val tomorrow = LocalDate.now().plus(1, ChronoUnit.DAYS)
val formattedTomorrow = tomorrow.format(DateTimeFormatter.ofPattern("EE, MMM d, yyy"))
java.time
private fun date24hours(s: String): String? {
val zone = ZoneId.of("Asia/Dubai")
val dateFormatter = DateTimeFormatter.ofPattern("EE, MMM d, uuuu", Locale.forLanguageTag("ar-OM"))
val tomorrow = LocalDate.now(zone).plusDays(1)
return tomorrow.format(dateFormatter)
}
I never tried writing Kotlin code before, so there’s probably one or more bugs, please bear with me.
In any case the date and time classes that you were using — Date and SimpleDateFormat— had serious design problems and are now long outdated. I recommend you use java.time, the modern Java date and time API, instead.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Related
I want to get the date time add minutes or hours, below code is working for me
def now = new Date();
use(groovy.time.TimeCategory) {
def new_date = now + 10.minutes;
}
Now the issue is the "10.minutes" is a variable come from other place, once I got it, it change to string.
So is there any method i can convert String (10.minutes) to like a object which i can use it to add with a date?
This works for me:
def now = new Date()
use(groovy.time.TimeCategory) {
String t = "10.minutes"
def new_date = now + evaluate(t)
println new_date
}
I'm new to Swift and not so familiar with date and time classes. I want to make an object of type Date that refers to sometime in the future (like several hours).
I'm not sure if this is going to be a UNIX timestamp or not.
How can I do that?
Swift Date (or NSDate) is a class in the Foundation framework. According to the docs:
The Date structure provides methods for comparing dates, calculating
the time interval between two dates, and creating a new date from a
time interval relative to another date. Use date values in conjunction
with DateFormatter instances to create localized representations of
dates and times and with Calendar instances to perform calendar
arithmetic.
So you'd want to make use of the Calendar class to do date conversions. Something like this should do the job:
func getDateTimeForHoursInTheFuture(hours: Int) -> Date {
var components = DateComponents();
components.setValue(hours, for: .hour);
let date: Date = Date();
let expirationDate = Calendar.current.date(byAdding: components, to: date);
return expirationDate!;
}
Of course it can be changed to work with minutes and seconds instead of hours.
You can format the output using:
extension Date {
func toDateTimeString() -> String {
let formatter = DateFormatter();
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
let myString = formatter.string(from: self);
return myString;
}
}
Just call the toDateTimeString() method on the result of getDateTimeForHoursInTheFuture function.
I am attempting to parse a date string of (almost) arbitrary length. The approach I had with SimpleDateFormat was something like this
private Date parseWithSimpleDateFormat(String dateString) throws ParseException {
String pattern = "yyyyMMddHHmmss".substring(0, dateString.length());
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.parse(dateString);
}
... which I want to do "better" with the new Date API. What I've come up with is the following
private static final DateTimeFormatter FLEXIBLE_FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("yyyy[MM[dd[HH[mm[ss]]]]]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
private Date parseWithDateTimeFormatter(String dateString) {
LocalDateTime localDateTime = LocalDateTime.parse(dateString, FLEXIBLE_FORMATTER);
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
Instant instant = zonedDateTime.toInstant();
return Date.from(instant);
}
with the following outcome
parseWithDateTimeFormatter("2016"); // works as intended
parseWithDateTimeFormatter("201605"); // Text '201605' could not be parsed at index 0
parseWithDateTimeFormatter("20160504"); // Text '20160504' could not be parsed at index 0
parseWithDateTimeFormatter("2016050416"); // Text '2016050416' could not be parsed at index 0
parseWithDateTimeFormatter("201605041636"); // Text '201605041636' could not be parsed at index 0
What am I doing wrong here, or how would I further troubleshoot this?
You can use this modified formatter in order to avoid parsing more than 4 digits for the year:
private static final DateTimeFormatter FLEXIBLE_FORMATTER =
new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.appendPattern("[MM[dd[HH[mm[ss]]]]]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
In contrast to other fields like month (MM) etc., the year field symbol y has no limitation to four digits as indicated by count of y-letters.
I have always converted a Date into a Calendar using the setTime() method
Date date = new Date()
def calendar.setTime(date)
Recently I found the .toCalendar() method.
Date date = new Date()
def calendar = date.toCalendar()
What's the difference between them and which should I use?
As you can here this method does exactly the same:
public static Calendar toCalendar(Date self) {
Calendar cal = Calendar.getInstance();
cal.setTime(self);
return cal;
}
Question 1: I have 2 fields to let user enter start date and end date, but in string format
- DateStart (string: yyyy/mm/dd hh:mm)
- DateEnd (string: yyyy/mm/dd hh:mm)
May I how to compare both datetime? I want to know total how many hours is difference between the both date.
Question 2: user will enter 1 returnDate (string: yyyy/mm/dd hh:mm) also in string format, may I know how to update the returnDate if I will need to add 55hours on the returnDate?
Thanks
Start by taking a look at SimpleDateFormat, which will allow you to convert the String value to a Date object.
For example...
try {
// Note hh is Hour in am/pm (1-12), based on you example, it's not possible
// now the day part (ie am or pm), you could supply aa as the am/pm marker
// or use HH which is Hour in day (0-23)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm");
Date date = sdf.parse("2014/04/11 4:46");
System.out.println(date);
} catch (ParseException exp) {
exp.printStackTrace();
}
Then you can use JodaTime to calculate the difference between the two dates, see How to find difference between two Joda-Time DateTimes in minutes for an example
It should be noted that you could skip the use of SimpleDateFormat and JodaTime all the way, check out String to joda LocalDate in format of "dd-MMM-yy" for an example of converting a String to a LocalDate using JodaTime
To add time to an existing Date, you can use either Calendar or JodaTime, see how to add days to java simple date format for an example of both
I would recommend that if you are using some kind of GUI, you might consider using one of the available date pickers as it will save you a lot of hassel
I suggest using Java8's java.util.time package
Example:
public static void main(String[] args) {
// example input
String dateString1 = "2014/04/10 00:00";
String dateString2 = "2014/04/11 23:59";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
LocalDateTime date1 = LocalDateTime.parse(dateString1, dtf);
LocalDateTime date2 = LocalDateTime.parse(dateString2, dtf);
// do your stuff with the dates...
}
Here is my solution:
String date1 = "2014/04/10 15:30";
String date2 = "2014/04/11 09:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
try {
Date parsedDate1 = sdf.parse(date1);
Date parsedDate2 = sdf.parse(date2);
double secs = (parsedDate2.getTime() - parsedDate1.getTime()) / 1000;
double hours = secs / 3600;
System.out.println(hours);
} catch (ParseException e) {
e.printStackTrace();
}
For adding hours to a date:
Date date = new Date(someDateObject.getTime() + 55 * 3600 * 1000);