comparison graal/com.oracle.truffle.ruby.runtime/src/com/oracle/truffle/ruby/runtime/core/RubyTime.java @ 13514:0fbee3eb71f0

Ruby: import project.
author Chris Seaton <chris.seaton@oracle.com>
date Mon, 06 Jan 2014 17:12:09 +0000
parents
children
comparison
equal deleted inserted replaced
13513:64a23ce736a0 13514:0fbee3eb71f0
1 /*
2 * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. This
3 * code is released under a tri EPL/GPL/LGPL license. You can use it,
4 * redistribute it and/or modify it under the terms of the:
5 *
6 * Eclipse Public License version 1.0
7 * GNU General Public License version 2
8 * GNU Lesser General Public License version 2.1
9 */
10 package com.oracle.truffle.ruby.runtime.core;
11
12 import java.text.*;
13 import java.util.*;
14
15 import com.oracle.truffle.ruby.runtime.objects.*;
16
17 /**
18 * Represents the Ruby {@code Time} class. This is a very rough implementation and is only really
19 * enough to run benchmark harnesses.
20 */
21 public class RubyTime extends RubyObject {
22
23 /**
24 * The class from which we create the object that is {@code Time}. A subclass of
25 * {@link RubyClass} so that we can override {@link #newInstance} and allocate a
26 * {@link RubyTime} rather than a normal {@link RubyBasicObject}.
27 */
28 public static class RubyTimeClass extends RubyClass {
29
30 public RubyTimeClass(RubyClass objectClass) {
31 super(null, objectClass, "Time");
32 }
33
34 @Override
35 public RubyBasicObject newInstance() {
36 return new RubyTime(this, milisecondsToNanoseconds(System.currentTimeMillis()));
37 }
38
39 }
40
41 private final long nanoseconds;
42
43 public RubyTime(RubyClass timeClass, long nanoseconds) {
44 super(timeClass);
45 this.nanoseconds = nanoseconds;
46 }
47
48 /**
49 * Subtract one time from another, producing duration in seconds.
50 */
51 public double subtract(RubyTime other) {
52 return nanosecondsToSecond(nanoseconds - other.nanoseconds);
53 }
54
55 @Override
56 public String toString() {
57 /*
58 * I think this is ISO 8601 with a custom time part. Note that Ruby's time formatting syntax
59 * is different to Java's.
60 */
61
62 return new SimpleDateFormat("Y-MM-d H:m:ss Z").format(toDate());
63 }
64
65 private Date toDate() {
66 return new Date(nanosecondsToMiliseconds(nanoseconds));
67 }
68
69 public static RubyTime fromDate(RubyClass timeClass, long timeMiliseconds) {
70 return new RubyTime(timeClass, milisecondsToNanoseconds(timeMiliseconds));
71 }
72
73 private static long milisecondsToNanoseconds(long miliseconds) {
74 return miliseconds * 1000000;
75 }
76
77 private static long nanosecondsToMiliseconds(long nanoseconds) {
78 return nanoseconds / 1000000;
79 }
80
81 private static double nanosecondsToSecond(long nanoseconds) {
82 return nanoseconds / 1e9;
83 }
84
85 }