Calculate the current date from given seconds - date

You have been provided the current time as the number of seconds that have elapsed since the start of this century (i.e since the beginning of 2000) as input. You have to compute the date that the input time corresponds to.Note that the output required is an integer in yyyymmdd format where yyyy corresponds to year, mm to month and dd to date.
Note:without using array concept
Example:
currDate(122352353)=20031117 ( it corresponds to 17th November 2003).

long timeInMilliSecs = 122352353000L;
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy");
try {
cal.setTime(sdf.parse("Jan 01 2000"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// all done
long d = cal.getTimeInMillis() + timeInMilliSecs;
cal.setTimeInMillis(d);
System.out.println(cal.get(Calendar.YEAR) + "" + (cal.get(Calendar.MONTH)+1) + "" + cal.get(Calendar.DATE));
Always work with timeinmillis. This will help you easily convert any date. So first thing is convert your 2000 date to millis and add the given date(122352353 in this case) to it after converting to millis. That is it! Now just convert the milli time to date.

Related

Kotlin: Getting the difference betweeen two dates (now and previous date)

Sorry if similar questions have been asked too many times, but it seems that there's one or more issues with every answer I find.
I have a date in the form of a String: Ex.: "04112005"
This is a date. 4th of November, 2005.
I want to get the difference, in years and days, between the current date and this date.
The code I have so far gets the year and just substracts them:
fun getAlderFraFodselsdato(bDate: String): String {
val bYr: Int = getBirthYearFromBirthDate(bDate)
var cYr: Int = Integer.parseInt(SimpleDateFormat("yyyy").format(Date()))
return (cYr-bYr).toString()
}
However, naturally, this is quite innacurate, since the month and days aren't included.
I've tried several approaches to create Date, LocalDate, SimpleDate etc. objects and using these to calcualate the difference. But for some reason I haven't gotten any of them to work.
I need to create a Date (or similar) object of the current year, month and day. Then I need to create the same object from a string containing say, month and year (""04112005""). Then I need to get the difference between these, in years, months and days.
All hints are appreciated.
I would use java.time.LocalDate for parsing and today along with a java.time.Period that calculates the period between two LocalDates for you.
See this example:
fun main(args: Array<String>) {
// parse the date with a suitable formatter
val from = LocalDate.parse("04112005", DateTimeFormatter.ofPattern("ddMMyyyy"))
// get today's date
val today = LocalDate.now()
// calculate the period between those two
var period = Period.between(from, today)
// and print it in a human-readable way
println("The difference between " + from.format(DateTimeFormatter.ISO_LOCAL_DATE)
+ " and " + today.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is "
+ period.getYears() + " years, " + period.getMonths() + " months and "
+ period.getDays() + " days")
}
The output for a today of 2020-02-21 is
The difference between 2005-11-04 and 2020-02-21 is 14 years, 3 months and 17 days
It Works Below 26 API level
There are too many formates of dates you just enter the format of date and required start date and end date. It will show you result. You just see different date formate hare and here if you need.
tvDifferenceDateResult.text = getDateDifference(
"12 November, 2008",
"31 August, 2021",
"dd MMMM, yyyy")
General method to calculate date difference
fun getDateDifference(fromDate: String, toDate: String, formater: String):String{
val fmt: DateTimeFormatter = DateTimeFormat.forPattern(formater)
val mDate1: DateTime = fmt.parseDateTime(fromDate)
val mDate2: DateTime = fmt.parseDateTime(toDate)
val period = Period(mDate1, mDate2)
// period give us Year, Month, Week and Days
// days are between 0 to 6
// if you want to calculate days not weeks
//you just add 1 and multiply weeks by 7
val mDays:Int = period.days + (period.weeks*7) + 1
return "Year: ${period.years}\nMonth: ${period.months}\nDay: $mDays"
}
For legacy Date functions below api 26 without running desugaring with Gradle plugin 4.0, java.time.* use:
fun getLegacyDateDifference(fromDate: String, toDate: String, formatter: String= "yyyy-MM-dd HH:mm:ss" , locale: Locale = Locale.getDefault()): Map<String, Long> {
val fmt = SimpleDateFormat(formatter, locale)
val bgn = fmt.parse(fromDate)
val end = fmt.parse(toDate)
val milliseconds = end.time - bgn.time
val days = milliseconds / 1000 / 3600 / 24
val hours = milliseconds / 1000 / 3600
val minutes = milliseconds / 1000 / 3600
val seconds = milliseconds / 1000
val weeks = days.div(7)
return mapOf("days" to days, "hours" to hours, "minutes" to minutes, "seconds" to seconds, "weeks" to weeks)
}
The above answers using java.time.* api is much cleaner and accurate though.

Getting time range between midnight and current time JDK 8

I have this method to calculate midnigt and current time as long values:
/**
* Returns the time range between the midnight and current time in milliseconds.
*
* #param zoneId time zone ID.
* #return a {#code long} array, where at index: 0 - midnight time; 1 - current time.
*/
public static long[] todayDateRange(ZoneId zoneId) {
long[] toReturn = new long[2];
LocalTime midnight = LocalTime.MIDNIGHT;
LocalDate today = LocalDate.now(zoneId);
LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);
ZonedDateTime todayMidnightZdt = todayMidnight.atZone(zoneId);
toReturn[0] = todayMidnightZdt.toInstant().toEpochMilli();
ZonedDateTime nowZdt = LocalDateTime.now().atZone(zoneId);
toReturn[1] = nowZdt.toInstant().toEpochMilli();
return toReturn;
}
Perhaps there is the simpler way to do that?
You could also do:
ZonedDateTime nowZdt = ZonedDateTime.now(zoneId);
ZonedDateTime todayAtMidnightZdt = nowZdt.with(LocalTime.MIDNIGHT);
I can't think of a simpler way to do it.
LocalDateTime vs ZonedDateTime
There's a (tricky) difference between LocalDateTime.now().atZone(zoneId) and ZonedDateTime.now(zoneId).
For the code below, I'm using a JVM in which the default timezone is America/Sao_Paulo and will try to get the current date and time in another timezone (Europe/London). At the moment I run this code, it's August 20th 2017, but in São Paulo the time is 17:56 and in London is 21:56.
When I do:
LocalDateTime nowLdt = LocalDateTime.now();
It creates a LocalDateTime with the current date and time in the JVM's default timezone. In this case, it'll get the current date and time in São Paulo's timezone (which is August 20th 2017, at 17:56):
2017-08-20T17:56:05.159
When I call the atZone method, it creates a ZonedDateTime that corresponds to this date and time in the specified zone:
ZoneId zoneId = ZoneId.of("Europe/London");
ZonedDateTime nowAtZone = nowLdt.atZone(zoneId);
The nowAtZone variable will be:
2017-08-20T17:56:05.159+01:00[Europe/London]
The same date (August 20th 2017) and time (17:56) in London timezone. Note that it's not the current date/time in London. If I get the equivalent epochMilli:
System.out.println(nowAtZone.toInstant().toEpochMilli());
It will be:
1503248165159
Now, if I don't use the LocalDateTime and direclty use the ZonedDateTime instead:
ZonedDateTime nowZdt = ZonedDateTime.now(zoneId);
It will get the current date and time in London, which will be:
2017-08-20T21:56:05.170+01:00[Europe/London]
Note that the time changed (it's 21:56). That's because right now, at this moment, that's the current time in London. If I get the epochMilli value:
System.out.println(nowZdt.toInstant().toEpochMilli());
The value will be:
1503262565170
Note that it's different from the first case using LocalDateTime (even if you ignore the difference in the milliseconds value, because the hour is different). If you want the current date and time at the specified timezone, you must use ZonedDateTime.now(zoneId).
Using LocalDateTime.now().atZone() not only gives a different result, but it will also change if you run in different JVM's, or if the JVM default timezone changes (someone might misconfigure it, or another application running in the same VM calls TimeZone.setDefault()).
Daylight Saving Time
Just remind about corner cases due to DST (Daylight Saving Time) issues. I'm gonna use the timezone I live in as example (America/Sao_Paulo).
In São Paulo, DST started at October 16th 2016: at midnight, clocks shifted 1 hour forward from midnight to 1 AM (and the offset changes from -03:00 to -02:00). So all local times between 00:00 and 00:59 didn't exist in this timezone (you can also think that clocks changed from 23:59:59.999999999 directly to 01:00). If I create a local date in this interval, it's adjusted to the next valid moment:
ZoneId zone = ZoneId.of("America/Sao_Paulo");
// October 16th 2016 at midnight, DST started in Sao Paulo
LocalDateTime d = LocalDateTime.of(2016, 10, 16, 0, 0, 0, 0);
ZonedDateTime z = d.atZone(zone);
System.out.println(z);// adjusted to 2017-10-15T01:00-02:00[America/Sao_Paulo]
When DST ends: in February 19th 2017 at midnight, clocks shifted back 1 hour, from midnight to 23 PM of 18th (and the offset changes from -02:00 to -03:00). So all local times from 23:00 to 23:59 existed twice (in both offsets: -03:00 and -02:00), and you must decide which one you want.
By default, it uses the offset before DST ends, but you can use the withLaterOffsetAtOverlap() method to get the offset after DST ends:
// February 19th 2017 at midnight, DST ends in Sao Paulo
// local times from 23:00 to 23:59 at 18th exist twice
LocalDateTime d = LocalDateTime.of(2017, 2, 18, 23, 0, 0, 0);
// by default, it gets the offset before DST ends
ZonedDateTime beforeDST = d.atZone(zone);
System.out.println(beforeDST); // before DST end: 2018-02-17T23:00-02:00[America/Sao_Paulo]
// get the offset after DST ends
ZonedDateTime afterDST = beforeDST.withLaterOffsetAtOverlap();
System.out.println(afterDST); // after DST end: 2018-02-17T23:00-03:00[America/Sao_Paulo]
Note that the dates before and after DST ends have different offsets (-02:00 and -03:00). This affects the value of epochMilli.
The above can also happen if you adjust the time using with method.
After modification the code now is much simpler:
/**
* Returns the time range between the midnight and current time in milliseconds.
*
* #param zoneId time zone ID.
* #return a {#code long} array, where at index: 0 - midnight time; 1 - current time.
*/
public static long[] todayDateRange(ZoneId zoneId) {
long[] toReturn = new long[2];
//ZonedDateTime nowZdt = LocalDateTime.now().atZone(zoneId);
ZonedDateTime nowZdt = ZonedDateTime.now(zoneId);//As suggested by Hugo (tested).
ZonedDateTime midZdt = nowZdt.with(LocalTime.MIDNIGHT);
toReturn[0] = midZdt.toInstant().toEpochMilli();
toReturn[1] = nowZdt.toInstant().toEpochMilli();
return toReturn;
}

How to get a list of days or a number of days in a month with GWT?

What is counter part of this code in GWT ?
public int returnAllDaysOf(2012,6){
Calendar calendar = Calendar.getInstance();
calendar.set(2012, Calendar.FEBRUARY, 1);
int daysOfFeb = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
return daysOfFeb;
}
Thanks in advance for your help.
I want to get the number of days of a month in the client side. I searched Google and StackOverFlow but didn't get anything.
for example Feb has 29 days, Match has 31 days and so on ...
I don't know a direct way, but you can calculate this value by adding one month to your date, and then calcualting the difference in days:
final Date myDate = ...;
final Date copyOfDate = CalendarUtil.copyDate(myDate);
CalendarUtil.addMonthsToDate(copyOfDate, 1);
final int daysBetween = CalendarUtil.getDaysBetween(myDate, copyOfDate);
Note: This even works if myDate is something like 2012-01-31. copyOfDate is then 2012-03-02 (because february doesn't have 31 days), and the result is correct again.
"Cheating" way to do it:
int daysInCurrentMonth = new Date(year-1900, month+1, 0).getDate();
I.E.
int daysInJanuary2014 = new Date(114, 1, 0).getDate();
basically set the Date object to the 0th day of the NEXT month, then get the day of the month.
NOTE: Date(int year, int month, int date) expects year=calendarYear-1900 (i.e. 2014=114) and month is 0-based (i.e. January would be month 0)
and yes, I know this constructor is deprecated, but I still use it.
DateField dfMois = new DateField();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dfMois.getValue());
Date date = dfMois.getValue();
Date dateCopy = dateFin;
dateCopy.setDate(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
if(date.getMonth() == Calendar.FEBRUARY + 1){
date.setDate(31 - dateCopy.getDate());
date.setMonth(date.getMonth()-1);
}
else{
date.setDate(dateCopy.getDate());
}
dfMois.setValue(date);
In your code... it work.

GWT converting current date to GMT

I am converting the current date to GMT time.
The result is in-consistent, due to this my date time calculations are going worng.
DateTimeFormat df = DateTimeFormat.getFormat("dd MMM yyyy hh:mm:ss");
String gmtStr = new Date().toGMTString().replace("GMT", "").trim();
long deptime= depTime - df.parse(gmtStr).getTime();
deptime = deptime / 1000;
seconds = (deptime % 60);
minutes = (deptime % 3600) / 60;
hours = (deptime / 3600);
Not sure what the best way is, but you could use the getTimezoneOffsert:
final Date gmtDate = new Date();
final Date offDate = new Date(gmtDate.getTime() + gmtDate.getTimezoneOffset() * 60 * 1000);
The offDate when displayed with DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_LONG) will still show the utc/gmt offset, because basically you have create a new time in the current timezone, but it matches the time of the GMT time and the long value returned from getTime() will be the number of milliseconds you can use in your calculation.

How do I convert microseconds into a timestamp?

I took this piece from an unencrypted .DAT file:
Code:
00 e1 27 17 6f e6 69 c0
Which translates to 63,374,851,375,000,000 in decimal. The units for the number are microseconds.
And this huge number cannot bypass the 1st January 1970 00:00:00 format; such a format that most converters use today.
So, yes. Is there such a converter that uses the 1st January of the year 1 format? Or how shall I make one?
And by the way, a timestamp is both date and time.
Thanks in advance!
You do not say what language are you using, if it is a .NET language, you can use: http://msdn.microsoft.com/en-us/library/z2xf7zzk.aspx for that constructor the input is in nanoseconds (are you sure that your number is in milliseconds and not in nanoseconds?).
If you are sure it is in milliseconds, the conversion to nanoseconds should be easy: 1 millisecond = 1 000 000 nanoseconds.
But I have the feeling that those are nanoseconds and not milliseconds...
Now that you have told us that it is in microseconds:
C# Example from decimal to yyyy dd MM hh:mm:ss
long microseconds = 63370738175000000;
long ticks = microseconds * 10;
DateTime timestamp = new DateTime(ticks);
Console.WriteLine(timestamp.ToString("yyyy dd MM hh:mm:ss"));
It prints:
2009 20 02 02:49:35
The other way around from yyyy dd MM hh:mm:ss to decimal
String dateString = "2009 20 02 02:49:35";
DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd MM hh:mm:ss",CultureInfo.CurrentCulture);
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
Console.WriteLine(microseconds);
It prints:
63370694975000000
And if you want it in hexadecimal just write:
Console.WriteLine(microseconds.ToString("X"));
Then it will print:
E1234FB3278DC0
If you want the answer in another programming language, please add that to you question.
In JAVA in order to convert microseconds into java.sql.Timestamp:
public static Timestamp getTimestampFromMicros(long pMicros) {
long millis = TimeUnit.MICROSECONDS.toMillis(pMicros);
long shaaritInMicros = pMicros - TimeUnit.MILLISECONDS.toMicros(millis);
Timestamp ts = new Timestamp(millis);
long nanos = ts.getNanos() + TimeUnit.MICROSECONDS.toNanos(shaaritInMicros);
ts.setNanos((int)nanos);
return ts;
}
Use below Java code to covert microseconds to date and time,
long msec = microseconds * 1/1000;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.format(msec);
Which will returns,
2016-01-27 03:41:12