Convert date to long (manually) - java

I want to convert a date to a long value (that is the milliseconds)
I have a date like
2/11/2014
I want to calculate the date in long (manual)
What I've tried
(2014 - 1970 ) * 31449600000 + 11 * 2592000000 + 2 * 604800000
This equals 1413504000000.
But http://www.fileformat.info/tip/java/date2millis.htm tells me that 1413504000000 is
Date (America/New_York) Thursday, October 16, 2014 8:00:00 PM EDT
Date (GMT) Friday, October 17, 2014 12:00:00 AM GMT
Date (short/short format) 10/16/14 8:00 PM
Where I'm wrong?
Again, I want to do this manually, not using java code.

Do not re-invent the wheel. Time/date calculations are notoriously difficult, even standard java library does not get it right. Use JodaTime:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class JodaTimeSample {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime date = DateTime.parse("2/11/2014", formatter);
System.out.println("Date: " + date.toString());
System.out.println("Millis: " + date.getMillis());
}
}

If you are sure you could do it manually (huh, why? - looks like homework), open JodaTime source code and copy it. You won't invent it better. Or even better open, read and then try to write it in your editor.

why you do manually to convert date into long or long into date, write a simple java code which give you correct results after convention, I am using the simple programme and convert it as per my user
public class test {
public static void main(String[] args) {
Date dt=new Date(Long.valueOf(1390973400983L));
System.out.println(dt.toString());
Calendar cal=Calendar.getInstance();
cal.set(2014, Calendar.JANUARY, 29, 11, 00, 0);
System.out.println(cal.getTimeInMillis());
System.out.println();
}
}
for more information visit here

Related

Need Calendar Instance only date (not time) and compare with date String in Kotlin as it lags

I need only date from Calendar Instance not the time. Whenever i used calendar object it returns the date with time.
val calendar = Calendar.getInstance()
calendar.time. // Mon Nov 09 11:41:29 GMT 2020
I change this by using SimpleDateFormat
SimpleDateFormat("dd/MM/yyyy").format(date)
09/09/2020
I am creating calendar so i have huge amount of data in list. I am adding data at specific date. So I am comparing dates with string date. My string date Format is look like this :-
20/05/2020
So there is too much performance issue like lagging the view. So is there any thing which i can use to avoid all this thing.
val calendarModel = dataList?.find {
SimpleDateFormat("dd/MM/yyyy").format(it.date) == item
}
Calendar#getTime returns a java.util.Date object representing this Calendar's time value which is a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT.
Thus, java.util.Date does not represent a real date or time or date-time object. When you print this millisecond value, your JVM calculates the date and time in its time-zone and when you print its object, you get what java.util.Date#toString returns. From this explanation, you must have already understood that this millisecond value will be the same irrespective of the timezone as it is not a timezone based value; rather, it is fakely represented by java.util.Date#toString as a timezone based value. Just to demonstrate what I have just said, look at the output of the following program:
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Date date = new Date();
System.out.println("Asia/Calcutta:");
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println(date.getTime());
System.out.println(date);
System.out.println("\nEurope/London:");
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
System.out.println(date.getTime());
System.out.println(date);
System.out.println("\nAfrica/Johannesburg:");
TimeZone.setDefault(TimeZone.getTimeZone("Africa/Johannesburg"));
System.out.println(date.getTime());
System.out.println(date);
System.out.println("\nAmerica/New_York:");
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
System.out.println(date.getTime());
System.out.println(date);
}
}
Output:
Asia/Calcutta:
1604747702688
Sat Nov 07 16:45:02 IST 2020
Europe/London:
1604747702688
Sat Nov 07 11:15:02 GMT 2020
Africa/Johannesburg:
1604747702688
Sat Nov 07 13:15:02 SAST 2020
America/New_York:
1604747702688
Sat Nov 07 06:15:02 EST 2020
The modern date-time API has real date-time classes. Given below is an overview of these classes:
As you can find in this table, there is a class, LocalDate which represents just date (consisting of a year, month, and day). Given below is a quick demo of the modern java.time API:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
// A date with the given year, month and day-of-month
LocalDate date = LocalDate.of(2010, Month.NOVEMBER, 7);
System.out.println(date);
// Today (in the JVM's timezone)
LocalDate today = LocalDate.now(); // Same as LocalDate.now(ZoneId.systemDefault())
System.out.println(today);
// Today at UTC
LocalDate todayAtUTC = LocalDate.now(ZoneOffset.UTC);
System.out.println(todayAtUTC);
// Today in India
LocalDate todayInIndia = LocalDate.now(ZoneId.of("Asia/Calcutta"));
System.out.println(todayAtUTC);
}
}
Output:
2010-11-07
2020-11-07
2020-11-07
2020-11-07
Learn more about the modern date-time API at Trail: Date Time.
Recommendation: The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. I suggest you should stop using them completely and switch to the modern date-time API.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Sum of two hours

I am developing an application where I want to add hours. But I don't know how to do to take into account change of day for example. If I have
9:45 pm + 3:30
it should give
1:15 am
Thanks for help
String time = "2:00 pm";
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
Date date = df.parse(time);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 3);
cal.add(Calendar.MINUTE, 30);
int h = cal.get(Calendar.HOUR_OF_DAY);
int m = cal.get(Calendar.MINUTE);
It will print 5:30 pm
EDIT: HOUR_OF_DAY provides a 24 h day
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
class SumHours{
public static void main(String[] args){
DateFormat dateFormat = new SimpleDateFormat("h:mm a");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,21);
cal.set(Calendar.MINUTE,45);
Date d = cal.getTime();
System.out.println(dateFormat.format(d));
cal.add(Calendar.HOUR, 3);
cal.add(Calendar.MINUTE, 30);
d = cal.getTime();
System.out.println(dateFormat.format(d));
}
}
Output:
9:45 PM
1:15 AM
Since so many have wanted to contribute an answer to this duplicate question (as I regard it), I thought it was time someone contributed the modern answer.
I know you are on Android Java 7, and until Java 8 comes to Android the modern answer requires you to use an external library, the ThreeTenABP. However, not only are the newer Java date and time classes in that library so much nicer to work with, when it comes to time arithmetic this is where they have one of their particularly strong points. So think about it, try it out. It’s also the future since the classes come built-in with Java 8 and later.
DateTimeFormatter timeFormatter
= DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
LocalTime startTime = LocalTime.of(21, 45);
Duration hoursToAdd = Duration.ofHours(3).plusMinutes(30);
LocalTime resultTime = startTime.plus(hoursToAdd);
System.out.println("" + startTime.format(timeFormatter) + " + " + hoursToAdd
+ " = " + resultTime.format(timeFormatter));
This prints:
9:45 PM + PT3H30M = 1:15 AM
I had wanted to give you lowercase pm and am and 3:30 as in your question. I admit we’re not quite there. In particular PT3H30M is peculiar if you haven’t learned ISO 8601 syntax. It means just 3 hours 30 minutes, easy enough when you know. Duration objects do not lend themselves well to formatting, it will help in Java 9, but as long as Java 8 hasn’t come to Android yet, let’s leave that. If you prefer lowercase pm, you may find the solution in this answer: displaying AM and PM in small letter after date formatting.
My code may not be that much shorter than the code in the other answers, but IMHO it is much easier to read.
Further links
ThreeTenABP
How to use ThreeTenABP in Android Project
Here is one of the decissions when you want to call this in anywhere:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeClass {
static String timeStart24 = "21:45";
static String timeStart = "09:45 PM";
static String timeStep = "3:30";
public String TimeClass(String start, String step) throws ParseException {
// Take hours and minutes apart
String[] time = step.split(":");
// Create format of time
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
SimpleDateFormat df24 = new SimpleDateFormat("HH:mm");
// Input begining time
Date from = df.parse(start);
System.out.println(df.format(from));
System.out.println(df24.format(from) + " - 24 hours format");
// Create calendar instance
Calendar cal = Calendar.getInstance();
cal.setTime(from);
// Inner method add of Calendar
cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
cal.add(Calendar.MINUTE, Integer.parseInt(time[1]));
System.out.println(df.format(cal.getTime()));
// System.out.print(df24.format(cal.getTime()));
return df.format(cal.getTime());
}
public static void main(String[] args) throws ParseException {
TimeClass tc = new TimeClass();
tc.TimeClass(timeStart, timeStep);
}
}
OUTPUT:
09:45 PM
21:45 - 24 hours format
01:15 AM

Long date conversion

I recently started supporting a system/application written in java.
I need to convert the below long date to a readable date as in 21 October 2016 :
Login date : 634940995544109969
Logout date : 63494125060775764
I tried different codes,I don't seem to come right.
A solution can be in java or c#.
You must add L at the end of the input .
Try following code .
public static void main(String[] args) {
long val = 634940995544109969L;
Date date=new Date(val);
System.out.println(DateFormat.getDateInstance().format(date));
}
The output will be in readable format .
For Ex : The above code will give Mar 5, 20122449 as output .
The milli seconds are converted into date.
You can check the correctness of output in the below link
Milliseconds to Date Conversion
You can also convert using below code
public static void main(String[] args) {
long lMilliSeconds = 634940995544109969L;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(lMilliSeconds);
System.out.println(cal.getTime());
}
Note-: I have considered that time is given in milliseconds.
Output-: Fri Mar 05 07:45:09 IST 20122449
try following in c#
long a = 634940995544109969;
DateTime dt = new DateTime(a);
Console.WriteLine(dt.ToString("dd MMM yyyy"));

how to get am/pm using simple date format

I want to get 12 hour clock time from milliseconds.I tried as follows
public class GetTimeFormat{
static SimpleDateFormat format;
public static String convertDate(String dateformat,Long date){
format = new SimpleDateFormat(dateformat);
String formattedDate = format.format(date);
return formattedDate;
}
public static void main(String args[])
{
long cal=1386059340010l;
String dateString=convertDate("MMM dd,yyyy HH:mm:ss a", cal);
System.out.println(dateString);
}
}
The corresponding date for the above milliseconds is Tue Dec 03 13:59:00 IST 2013
So I thought I will get formatted date as Dec 03,2013 1:59:00 PM
but instead I am getting Dec 03,2013 13:59:00 PM
there is no need for am/pm in 24 hour clock and in 12 hour clock am/pm is required
But In my way I am getting time in 24 hour format + PM.
Can Any body tell me whats the mistake here?
Another question is why in ideone its showing Dec 03,2013 08:29:00 AM
Not only in ideone but I have checked many online compilers and every where its showing the same but in local machine time is different(13:59)
You need to use a lowercase h in your format pattern:
String dateString = convertDate("MMM dd,yyyy h:mm:ss a", cal);
You can see here for a full reference of format patterns, including an example that covers this specific case.

How to create the date explicitly in java?

I have tried this code. I got the output but not the right one...
//Iam getting my answer after the following changes below...
package patternsamp;
import java.io.*;
import java.util.*;
public class Mydate
{
static void test()
{
Date da = new Date(5,9,2014,07,00,00);
System.out.println(da.toGMTString());
}
public static void main(String[] args)
{
Mydate.test();
}
}
//I made the changes like this.....
Date da = new Date(114,8,5,12,30,0);
OUTPUT: 5 Sep 2014 07:00:00 GMT
This gives me right output... Thanks for your support friends.....
To get the sep 5 as output, shuold be given as 5-9,
Try using simpledateformat:
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "5-9-2014 07:00:00";
Date date = sdf.parse(dateInString);
System.out.println(date);
Quoting from Java Doc
Date(int year, int month, int date, int hrs, int min, int sec)
`Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec).`
Avoid using Date constructor (to set dates) at all, incase you insist maintain correct order of parameters, your code should look like this:-
package patternsamp;
import java.io.*;
import java.util.*;
public class Mydate
{
static void test()
{
Date da = new Date(114,9,5,07,00,00);
System.out.println(da.toGMTString());
}
public static void main(String[] args)
{
Mydate.test();
}
Note that I am using 114 in the year (and not 2014), since according to doc
A year y is represented by the integer y - 1900.
Hence to represent 2014 , you have to 2014-1900, which is 114.
if your project imported commons-lang.jar
you can get the Date object from String like this:
DateUtils.parseDate("2014-08-20",new String[]{"yyyy-MM-dd"})
Joda-Time
So much easier and sensible to use the Joda-Time library rather than the notoriously troublesome bundled java.util.Date and .Calendar classes. To specify a year, you specify a year (2014 rather than 114). To specify a month, you specify a month (9 means September rather than 8).
DateTime dateTime = new DateTime( 2014, 9, 5, 7, 0, 0, DateTimeZone.UTC );
If you must have a java.util.Date object, convert.
java.util.Date date = dateTime.toDate();

Categories