Printing out datetime in a specific format in Java? - java

I want to print out datetime in java in a specific format. I have this C# code which prints out the datetime in this format.
DateTime value = new DateTime(2010, 1, 18);
Console.WriteLine(value);
Console.WriteLine(value == DateTime.Today);
The result is - 1/18/2010 12:00:00 AM
Now, I want to write a java code that prints out the datetime in the same format. I used the joda.time library. This is what I tried so far.
DateTime today = new DateTime();
System.out.println(today.toString(“yyyy-MMM-dd”));
How can I pass the year,month and day as the constructor in the DateTime in java and print out in the above format.

Approach 1: Using java.time.LocalDateTime. (Strongly Preferred)
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43
Approach 2: Using java.util.Date.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
Approach 3: Using java.util.Calendar.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43

If you need date in 24 hour system then use this approach
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date custDate = new Date();
System.out.println(sdf.format(custDate));
Please note in 24 hour system there is no need to show AM/PM.
If you want date in 12 hour system then use below approach
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date custDate = new Date();
System.out.println(sdf.format(custDate));
"a" in the date format will help to show AM/PM.
Please import below classes for above code to work
java.text.SimpleDateFormat
java.util.Date

LocalDate.of(2010, 1, 18).atStartOfDay().format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a"))
or
LocalDate.of(2010, 1, 18).atTime(12, 0, 0).format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a"));
if you want to add the time too

Please try to this one
public void Method(Datetime time)
{
time.toString("yyyy-MM-dd'T'HH:mm:ss"));
}

Related

How do I change 'AM' to 'PM' in a Date Object JAVA [duplicate]

This question already has answers here:
Comparing two times in android
(4 answers)
12:xx shown as 00:xx in SimpleDateFormat.format("hh:mm:ss")
(1 answer)
Closed 3 years ago.
I am trying to use Date objects and calculate time differences for an android app. But I face a problem when time is in '12:00'. I mean when I input date as 12:12:00 Java AM/PM formatter returns 12:12:00AM but it should be 12:12:00PM.
I can't find any way to solve it.
Date date = new Date();
String stringDate = "2019-09-13 12:12:00";
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date6 = formatter6.parse(stringDate);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
System.out.println(sdf.format(date6));
It returns 12:12:00 AM
but it should be 12:12:00 PM for correct calculations
In Line:
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
The hh makes sure that hours are parsed as AM/PM values b/w 1-12. To get the desired result, you can use HH marker which parses hour values between 0-23. So, the code should be:
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Use DateTimeFormatter and LocalDateTime
String stringDate = "2019-09-13 12:12:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(stringDate, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("hh:mm:ss a");
System.out.println(formatter2.format(date));
You might also want to set a Locale for your second formatter depending on where you live.
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.US);
System.out.println(formatter2.format(date));
12:12:00 PM
Pass the AM/PM in the time
Date date = new Date();
String stringDate = "2019-09-13 12:12:00 PM";
SimpleDateFormat formatter6 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date date6 = formatter6.parse(stringDate);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
System.out.println(sdf.format(date6));
Try to do it the modern way, that is using java.time:
String stringDate = "2019-09-13 12:12:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime datetime = LocalDateTime.parse(stringDate, dtf);
DateTimeFormatter dtfA = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");
System.out.println(datetime.format(dtfA));
// receive the time part and format it
LocalTime timePart = datetime.toLocalTime();
DateTimeFormatter tf = DateTimeFormatter.ofPattern("hh:mm:ss a");
System.out.println(timePart.format(tf));
This outputs
2019-09-13 12:12:00 PM
12:12:00 PM
on my system.
Note that your pattern String used for parsing is wrong since you are not using capital "H" for the hours of day, but "h" instead. That will definitely not work (correctly).
Two solutions,
1.
Date date = new Date();
String stringDate = "2019-09-13 12:12:00 PM";
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
2.
Date date = new Date();
String stringDate = "2019-09-13 12:12:00";
SimpleDateFormat formatter6=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
If you are using java 8 or above then you should definitely use LocalDateTime and DateTimeFormatter makes it way easier to work with date times.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a");
String am = LocalDateTime.now().format(formatter);
String pm = LocalDateTime.now().plusHours(2).format(formatter);
System.out.println(am);
System.out.println(pm);
Now I am assuming that I run this code during am hours just 2 hours before it changes to pm you can also try out #Joakim Danielson answer which should not be dependent on when it is run.
checkout the documentation for LocalDateTime and DateTimeFormatter

Convert Local time to UTC with timezoneoffset in Java

I have a local date/timestamp and I have a timezone offset stored in String format (myStringTimeStamp variable name below). I need to convert the local date/timestamp to UTC time.
The format the timestamp is in is: yyyy-MM-dd HH:mm:ss
I have tried variations on:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Convert timestamp to date
Date d = sdf.parse(myStringTimeStamp, new ParsePosition(0));
newTimeStamp = sdf.format(d);
But I can't seem to figure out the right formula. Any help?
I can't use 3rd party libraries/frameworks.
Problem seems to be because you're setting the target timezone before parsing.
First parse, then set timezone, and finally format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
//Convert timestamp to date
Date d = sdf.parse(myStringTimeStamp, new ParsePosition(0));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
newTimeStamp = sdf.format(d);
Did you try:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
//Convert timestamp to date
Date d = sdf.parse(myStringTimeStamp, new ParsePosition(0));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
newTimeStamp = sdf.format(d);

Java Date format weird

I have an issue where I would like to get the start of the day, however it seems to be setting it to 12:00 via automatic.
SimpleDateFormat dfFull = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String todayDate = dfFull.parse("2014-06-06 00:00:00");
today = dfFull.format(todayDate);
System.out.println(today);
Why is this spitting out:
2014-06-06 12:00:00
The 12:00:00 is the issue
That is because hh represents the hour in 12 hour format. You need to use HH instead.
SimpleDateFormat dfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Have a look at the docs for more info.
Also, on a side note, there is a typo in your code.
SimpleDateFormat dfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date todayDate = dfFull.parse("2014-06-06 00:00:00"); // todayDate must be of type Date and not String
String today = dfFull.format(todayDate); // today should be of type String
System.out.println(today);
You should use HH for hours in this case.
SimpleDateFormat dfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String todayDate = dfFull.parse("2014-06-06 00:00:00");
today = dfFull.format(todayDate);
System.out.println(today);
Now you will get the out put as
2014-06-06 00:00:00
And again if you use hh that mean you are using 12 hour format while HH means 24 hour format
So

trouble with local time

i use these codes to get my local time:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar currenDdate = Calendar.getInstance(TimeZone.getDefault());
System.out.print("Last update: "+dateFormat.format(currenDdate.getTime()));
or:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar currenDdate = Calendar.getInstance(getTimeZone("GMT+3.5"));
System.out.print("Last update: "+dateFormat.format(currenDdate.getTime()));
but non of them give the local time, they are both giving me GMT
what is the problem?
NOTE: I am using eclipse and android programming, the codes above correctly work in java but in android it is not!
instead of system.out.print() i use a textview to show the time
TextView date = (TextView) findViewById(R.id.gold_textView1);
date.setText("Last update: "+dateFormat.format(currenDdate.getTime()));
please help me find the problem
Try Date currentDate = new Date() instead of the Calendar object. Your System.out.print() call won't change. Also, double check your system to make sure its default timezone is set correctly.
Have you tried like this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getDefault());
Calendar currenDdate = Calendar.getInstance(TimeZone.getDefault());
System.out
.print("Last update: " + dateFormat.format(currenDdate.getTime()));
Instead of Calendar you need to set your TimeZone on SimpleDateFormat:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+0330"));
// prints: Last update: 2013/07/31 18:46:24 +0330
System.out.println("Last update: " + dateFormat2.format(currenDdate.getTime()));
This is required because SimpleDateFormat uses a Calendar instance of its own internally.
See SimpleDateFormat#setTimeZone()
public void setTimeZone(TimeZone zone)
{
calendar.setTimeZone(zone);
}
Notice, the date format pattern also includes the time zone letter Z to include it in the display.
Try this, use JodaTime http://www.joda.org/joda-time/
DateTimeZone dateTimeZoneUTC = DateTimeZone.UTC;
DateTime dateTimeUTC = new DateTime().withZone(dateTimeZoneUTC);
DateTimeZone dateTimeZoneLocal = DateTimeZone.getDefault();
DateTime dateTimeLocal = dateTimeUTC.withZone(dateTimeZoneLocal);
DateTimeZone dateTimeZoneOffset = DateTimeZone.forID("-03:00");
DateTime dateTimeOffset = dateTimeLocal.withZone(dateTimeZoneOffset);
// Airport Current Time hh/mm
DateTimeFormatter timeFormat = DateTimeFormat.forPattern("hh/mm").withZone(dateTimeZoneOffset);
currentTime.setText(timeFormat.print(dateTimeOffset));

Current Date & Time in Java

I want the current date and time in the following format :
Date :YYYYMMDD
Time : HHMMSS
I tried the following
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(new Date().getTime());
By this I am getting the desired date output but the time is coming in this way 1341837848290.
The expected is HHMMSS.
Use format()
System.out.println(new SimpleDateFormat("HH:mm:SS").format(new Date()));
Date instance doesn't have any property to hold custom format, So you need to format the date instance to String with your custom format HH:mm:SS (See API doc for more detail)
See
IDEOne demo
try this
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
DateFormat timeFormat = new SimpleDateFormat("HHmmss");
Date d=new Date();
System.out.println(timeFormat.format(d);
Did you check out the joda-time library? Link here
With joda-time, you could easily call new DateTime(), call toString() on it and have this output, which may be more what you want:
public static void main(final String[] args) {
final DateTime d = new DateTime();
System.out.println(d.toString());
}
Output: 2012-07-09T14:54:13.366+02:00
Joda-Time is very powerful on the plus side. Of course, this is an extra lib you need to include, and if this is not possible or desired, another approach would probably be better.
I tried this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
Date date = Calendar.getInstance().getTime();
System.out.println(sdf.format(date));
Yields:
20120709 145518
First section is the date (20120709), the second section is the time(145518).
It seems that you have been using the wrong notation. I would recommend you take a look here for full details.
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:SS");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
for more formatting refer API Doc

Categories

Resources