Date manipulation: Difference between revisions

From Rosetta Code
Content added Content deleted
(new task with Tcl implementation)
 
(Added Java)
Line 1: Line 1:
{{task|Text processing}}
{{task|Text processing}}
Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format.
Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format.
=={{header|Java}}==
<lang Java>import java.util.Date;
import java.text.SimpleDateFormat;
public class DateManip{
public static void main(String[] args) throws Exception{
String dateStr = "March 7 2009 7:30pm EST";


SimpleDateFormat sdf = new SimpleDateFormat("MMMM d yyyy h:mma zzz");
Date date = sdf.parse(dateStr);
date.setTime(date.getTime() + 43200000l);

System.out.println(sdf.format(date));
}

}</lang>
Output:
<pre>March 8 2009 8:30AM EDT</pre>
or using <tt>System.out.println(date);</tt> as the last line:
<pre>Sun Mar 08 08:30:00 EDT 2009</pre>
=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}

Revision as of 20:33, 13 May 2009

Task
Date manipulation
You are encouraged to solve this task according to the task description, using any language you may know.

Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format.

Java

<lang Java>import java.util.Date; import java.text.SimpleDateFormat; public class DateManip{

   public static void main(String[] args) throws Exception{

String dateStr = "March 7 2009 7:30pm EST";

SimpleDateFormat sdf = new SimpleDateFormat("MMMM d yyyy h:mma zzz");

Date date = sdf.parse(dateStr);

date.setTime(date.getTime() + 43200000l);

System.out.println(sdf.format(date));

   }

}</lang> Output:

March 8 2009 8:30AM EDT

or using System.out.println(date); as the last line:

Sun Mar 08 08:30:00 EDT 2009

Tcl

Works with: Tcl version 8.5

<lang tcl>set date "March 7 2009 7:30pm EST" set epoch [clock scan $date -format "%B %d %Y %I:%M%p %z"] set later [clock add $epoch 12 hours] puts [clock format $later] ;# Sun Mar 08 08:30:00 EDT 2009</lang>

Note the transition into daylight savings time in the interval (in the Eastern timezone).