Date manipulation: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Java)
(C)
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|C}}==

<lang c>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define BUF_LEN 100

int main()
{
struct tm ts;
time_t t;
const char *d = "March 7 2009 7:30pm EST";
char buf[BUF_LEN];
strptime(d, "%B %d %Y %I:%M%p %Z", &ts);
/* ts.tm_hour += 12; instead of t += 12*60*60
works too. */
t = mktime(&ts);
t += 12*60*60;
printf("%s", ctime(&t));

return EXIT_SUCCESS;
}</lang>

=={{header|Java}}==
=={{header|Java}}==
<lang Java>import java.util.Date;
<lang Java>import java.util.Date;

Revision as of 22:42, 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.

C

<lang c>#include <stdio.h>

  1. include <stdlib.h>
  2. include <time.h>
  1. define BUF_LEN 100

int main() {

 struct tm ts;
 time_t t;
 const char *d = "March 7 2009 7:30pm EST";
 char buf[BUF_LEN];
 
 strptime(d, "%B %d %Y %I:%M%p %Z", &ts);
 /* ts.tm_hour += 12; instead of t += 12*60*60
    works too. */
 t = mktime(&ts);
 t += 12*60*60;
 printf("%s", ctime(&t));
 return EXIT_SUCCESS;

}</lang>

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).