Skip to content

Commit

Permalink
Merge pull request #39 from smallwins/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
spencermountain authored Feb 1, 2018
2 parents 4642d27 + 9e400fe commit 9143c35
Show file tree
Hide file tree
Showing 18 changed files with 193 additions and 48 deletions.
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
.DS_Store
.jshintrc
.env
immutable.js
spacetime.js
node_modules/
.nyc_output
npm-debug.log
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ s = spacetime('July 2, 2017 5:01:00') // ISO
s = spacetime(1489520157, 'Canada/Pacific')
s = spacetime('2019/05/15', 'Canada/Pacific')

// or set the offset right in the date-string (ISO-8601)
s = spacetime('2017-04-03T08:00:00-0700')
// 'Etc/GMT-7'

// Some helpers
s = spacetime.now()
s = spacetime.today() // This morning
Expand Down Expand Up @@ -102,7 +106,7 @@ const ImmutableSpacetime = require('spacetime/immutable')
const day0 = new ImmutableSpacetime([2018, 0, 1])

day0.format('nice') // January 1st
day0.add(3, 'days').format('nice') // January 4th
day0.add(3, 'days').format('nice') // January 4th
day0.format('nice') // January 1st!
```

Expand Down
6 changes: 6 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,9 @@
* support unix/unicode time-formating basic-level
* add `.era()` get/set method
* found 6 or 7 wrong offsets

## v3.0.0
* fallback to UTC, instead of PST if no `Intl` is present
* support passing-in offsets as ISO_8601 date-strings
* add epoch-seconds warning msg
* allow getting/setting new timezones
2 changes: 2 additions & 0 deletions immutable.js

Large diffs are not rendered by default.

22 changes: 18 additions & 4 deletions microsite/src/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
'use strict';
import React from 'react';
import Year from './year';
import styler from 'react-styling/flat';
import ReactDOM from 'react-dom';
import spacetime from '../../builds/spacetime';
import spacetime from '../../src/';
import { scaleLinear } from 'd3-scale';
import Radium from 'radium';
window.spacetime = spacetime

function doit() {
console.time('test')
for (let i = 0; i < 10000; i += 1) {
let r = parseInt(Math.random() * 5, 10)
let s = spacetime([1980 + r, r, 20 + r], 'UTC')
s.format('date')
}
console.timeEnd('test')
}

setInterval(() => {
doit()
}, 8000)

const months = [
'january',
Expand Down Expand Up @@ -122,7 +135,7 @@ class App extends React.Component {
let {state, css} = this;
let s = state.s;
const methods = [
'timeOfDay',
'time',
'dayName',
'dayOfYear',
'week',
Expand All @@ -131,6 +144,7 @@ class App extends React.Component {
'leapYear',
];
let arr = methods.map((str, i) => {
console.log(str)
return (
<div key={i}>
<span style={css.key}>{str + ': '}</span>
Expand Down
12 changes: 1 addition & 11 deletions microsite/src/year.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
'use strict';
import React from 'react';
import styler from 'react-styling/flat';
import ReactDOM from 'react-dom';
import spacetime from '../../builds/spacetime';
import { scaleLinear } from 'd3-scale';
import Radium from 'radium';

const months = [
'january',
Expand All @@ -21,15 +16,9 @@ const months = [
'december',
];

const style = styler`
container
position:relative
`;

class Year extends React.Component {
constructor(props) {
super();
this.css = style;
this.state = {};
this.width = props.width || 600;
this.scale = scaleLinear().domain([0, 12]).range([0, this.width]);
Expand All @@ -46,6 +35,7 @@ class Year extends React.Component {
if (meta.current.isDST) {
return <rect key={i} x={month * i} y={18} width={month} height={2} fill={'orange'} opacity={0.8}/>;
}
return null
});
let now = s.progress().year;
let nowX = now * this.width;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "spacetime",
"version": "2.2.0",
"version": "3.0.0",
"description": "represent dates in remote timezones",
"main": "./spacetime.js",
"license": "Apache-2.0",
Expand Down
32 changes: 27 additions & 5 deletions scratch.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
const ist = require('./immutable')
const spacetime = require('./src/index')

let day0 = ist.now()
console.log(day0.format('nice'))
console.log(day0.add(2, 'days').format('nice'))
console.log(day0.subtract(1, 'days').format('nice'))
// const s = spacetime(1517509494000, 'UTC')
// s.timezones = {
// 'UTC/fun': {
// o: 9,
// h: 'n'
// }
// }
// s.goto('UTC/fun')
// s.debug()

// let s = spacetime([1970, 1, 1], 'UTC')
// console.log(new Date(s.epoch * 1000))
//
// s = spacetime([2054, 10, 1], 'UTC')
// console.log(new Date(s.epoch / 1000))

// new handy warning in [email protected]
// Fun fact: we're only subject-to these 'off-by-thousand' date errors between Sept 2001 and Jan 2057.

console.time('test')
for (let i = 0; i < 10000; i += 1) {
let r = parseInt(Math.random() * 5, 10)
let s = spacetime([1980 + r, r, 20 + r], 'UTC')
s.format('date')
}
console.timeEnd('test')
3 changes: 3 additions & 0 deletions spacetime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/* spacetime v3.0.0
*/
4 changes: 2 additions & 2 deletions src/findTz.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict'
const Spacetime = require('./spacetime');
const timezones = require('../data');
// const timezones = require('../data');

exports.whereIts = function(a, b) {
let start = new Spacetime(null);
Expand All @@ -15,7 +15,7 @@ exports.whereIts = function(a, b) {

let startHour = start.hour();
let endHour = end.hour();
let tzs = Object.keys(timezones).filter(tz => {
let tzs = Object.keys(start.timezones).filter(tz => {
let m = new Spacetime(null, tz);
let hour = m.hour();
//do 'calendar-compare' not real-time-compare
Expand Down
13 changes: 13 additions & 0 deletions src/input/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ const fns = require('../fns');
// Full Date "Wednesday March 25 2015"
//=========================================

//-- also -
// if the given epoch is really small, they've probably given seconds and not milliseconds
// anything below this number is likely (but not necessarily) a mistaken input.
// this may seem like an arbitrary number, but it's 'within jan 1970'
// this is only really ambiguous until 2054 or so
const minimumEpoch = 2500000000

//support [2016, 03, 01] format
const handleArray = function(s, arr) {
let order = ['year', 'month', 'date', 'hour', 'minute', 'second', 'millisecond'];
Expand All @@ -34,8 +41,13 @@ const handleObject = function(s, obj) {

//find the epoch from different input styles
const parseInput = (s, input) => {
//if we've been given a epoch number, it's easy
if (typeof input === 'number') {
s.epoch = input;
if (input > 0 && input < minimumEpoch) {
console.warn(' - Warning: You are setting the date to January 1970.')
console.warn(' - did input seconds instead of milliseconds?')
}
return;
}
//set tmp time
Expand Down Expand Up @@ -73,6 +85,7 @@ const parseInput = (s, input) => {
return;
}
}
console.warn('Warning: couldn\'t parse date-string: \'' + input + '\'')
s.epoch = null;
s.valid = false;
return;
Expand Down
43 changes: 42 additions & 1 deletion src/input/strParse.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';
const walkTo = require('../methods/set/walk');
const months = require('../data/months');
// const zones = require('../../data');

const parseHour = function(s, str) {
str = str.replace(/^\s+/, ''); //trim
Expand All @@ -16,13 +17,53 @@ const parseHour = function(s, str) {
}
}
};
const parseOffset = function(s, offset) {
if (!offset) {
return s
}
//this is a fancy-move
if (offset === 'Z') {
offset = '+0000'
}
//support "+01:00"
if (/:00/.test(offset) === true) {
offset = offset.replace(/:00/, '')
}
//support "+01:30"
if (/:00/.test(offset) === true) {
offset = offset.replace(/:00/, '.5')
}
let num = parseInt(offset, 10)
//divide by 100 or 10 - , "+0100", "+01"
if (Math.abs(num) > 100) {
num = num / 100
}
// console.log(offset, num)
let current = s.timezone().current.offset
if (current === num) { //we cool..
return s
}
//okay, try to match it to a utc timezone
if (num >= 0) {
num = '+' + num
}

let tz = 'Etc/GMT' + num
let zones = s.timezones
if (zones[tz]) {
// console.log('changing timezone to: ' + tz)
s.tz = tz
}
return s
}

const strFmt = [
//iso-this 1998-05-30T22:00:00:000Z, iso-that 2017-04-03T08:00:00-0700
{
reg: /^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})T([0-9:-\\.]+)(Z|[0-9\-\+:]+)?$/,
reg: /^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})T([0-9.:]+)(Z|[0-9\-\+:]+)?$/,
parse: (s, arr) => {
let month = parseInt(arr[2], 10) - 1;
parseOffset(s, arr[5]);
walkTo(s, {
year: arr[1],
month: month,
Expand Down
9 changes: 8 additions & 1 deletion src/methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,14 @@ const methods = {
console.log('')
console.log(format(this, 'full-short'))
return this
}
},
debug: function() {
let tz = this.timezone()
let date = this.format('MM') + ' ' + this.format('date-ordinal') + ' ' + this.year()
date += '\n - ' + this.format('time')
console.log('\n\n', date + '\n - ' + tz.name + ' (' + tz.current.offset + ')')
return this
},
}
methods.inDST = methods.isDST
methods.round = methods.nearest
Expand Down
11 changes: 11 additions & 0 deletions src/spacetime.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const guessTz = require('./timezone/guessTz')
const timezone = require('./timezone/index')
const handleInput = require('./input')
const methods = require('./methods')
let zones = require('../data')

//fake timezone-support, for fakers (es5 class)
const SpaceTime = function(input, tz) {
Expand All @@ -26,6 +27,16 @@ const SpaceTime = function(input, tz) {
return d
}
})
//add this data on the object, to allow adding new timezones
Object.defineProperty(this, 'timezones', {
get: function() {
return zones
},
set: function(obj) {
zones = obj
return obj
}
})
//parse the various formats
handleInput(this, input)
}
Expand Down
33 changes: 18 additions & 15 deletions src/timezone/guessTz.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,29 @@
//find the implicit iana code for this machine.
//safely query the Intl object
//based on - https://bitbucket.org/pellepim/jstimezonedetect/src
const fallbackTZ = 'Canada/Pacific'; //eeeek!
const fallbackTZ = 'Etc/UTC'; //

const guessTz = () => {
if (
typeof Intl === 'undefined' ||
typeof Intl.DateTimeFormat === 'undefined'
) {
return fallbackTZ;
//this Intl object is not supported often, yet
const safeIntl = function() {
if (typeof Intl === 'undefined' || typeof Intl.DateTimeFormat === 'undefined') {
return null;
}
let format = Intl.DateTimeFormat();
if (
typeof format === 'undefined' ||
typeof format.resolvedOptions === 'undefined'
) {
return fallbackTZ;
if (typeof format === 'undefined' || typeof format.resolvedOptions === 'undefined') {
return null;
}
let timezone = format.resolvedOptions().timeZone;
if (timezone && (timezone.indexOf('/') > -1 || timezone === 'UTC')) {
return timezone;
if (!timezone || (timezone.indexOf('/') === -1 && timezone === 'UTC')) {
return null
}
return timezone;
}

const guessTz = () => {
let timezone = safeIntl()
if (timezone === null) {
return fallbackTZ
}
return fallbackTZ;
return timezone
};
module.exports = guessTz;
3 changes: 2 additions & 1 deletion src/timezone/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict';
const zones = require('../../data');
// const zones = require('../../data');
const summerTime = require('./summerTime')

const parseDst = dst => {
Expand All @@ -12,6 +12,7 @@ const parseDst = dst => {
//get metadata about this timezone
const timezone = s => {
let tz = s.tz;
let zones = s.timezones
if (!zones[tz]) {
console.warn("Warn: could not find given or local timezone - '" + tz + "'");
return {
Expand Down
Loading

0 comments on commit 9143c35

Please sign in to comment.