Date manipulation: Difference between revisions
(C) |
m (→{{header|C}}: note) |
||
Line 26: | Line 26: | ||
return EXIT_SUCCESS; |
return EXIT_SUCCESS; |
||
}</lang> |
}</lang> |
||
Note: <code>ctime</code> treats the date as local, so that it is like the timezone information were discarded (to see it I must change it into March 28... no matter the timezone specified) |
|||
=={{header|Java}}== |
=={{header|Java}}== |
Revision as of 01:02, 14 May 2009
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>
- 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>
Note: ctime
treats the date as local, so that it is like the timezone information were discarded (to see it I must change it into March 28... no matter the timezone specified)
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
<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).