1

I am new to Java and trying to use Calendar object to get date and time of now as a string. I am particularly stuck at object and object conversions.

Here is the format I need (as a string): 2016-03-30T14:21:00Z

If I could just get the date and time format right, I could play around with the string but I am struggling with deprecated methods.

Thank you for replies

Ben77
  • 65
  • 2
  • 9
  • `System.out.println(DateFormat.getDateTimeInstance().format(new Date()))`, if you have a particular date format you need you can use `SimpleDateFormat` to customise the format. Alternatively, you can use Java 8's Time API which has a number of predefined formatters to handle those types of formats, [`DateTimeFormatter.ISO_DATE_TIME`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_DATE_TIME) comes to mind – MadProgrammer Mar 30 '16 at 06:47
  • *"I could play around with the string"* is a scary thought, better to use the Time API or Joda Time to manipulate the actual time value – MadProgrammer Mar 30 '16 at 06:53
  • @Ben77 Please search Stack Overflow before posting. The basic date-time questions have already been asked and answered. – Basil Bourque Mar 30 '16 at 19:37

2 Answers2

3

Your best bet is to start using Java 8's new Time API (or JodaTime if you can't use Java 8)

LocalDateTime now = LocalDateTime.now();
String isoFormat = DateTimeFormatter.ISO_INSTANT.format(now.toInstant(ZoneOffset.UTC));
System.out.println(isoFormat);

outputs 2016-03-30T17:51:38.639Z (when I tested it)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

Solved my question using this link:

http://beginnersbook.com/2013/05/current-date-time-in-java/

Thanks for replies, I will also look into Java 8' time API

Ben77
  • 65
  • 2
  • 9