Hi I am using Ember+moment.js to format date in my ember helpers.
I am getting the following date from the service
Tue Aug 23 2016 09:43:53 GMT+0200 (W. Europe Daylight Time)
In my ember helper class i am able to format date using following code :
var formattedDate = moment(date).format('DD/MM/YYYY h:mm a');
I am getting the following output :
23/08/2016 9:43 am
Expected Output : 23/08/2016 9:43 am GMT
How can i specify the timezone flag in the format function?
Any help should be appreciated.
Install ember-moment - ember install ember-moment
Install ember-cli-moment-shim - ember install ember-cli-moment-shim
stop and start ember server
To enable moment timezone, need to include moment:{ includeTimezone: 'all' } in config\environment.js
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'App-Name',
environment: environment,
baseURL: '/',
locationType: 'auto',
moment: {
// Options:
// 'all' - all years, all timezones
// '2010-2020' - 2010-2020, all timezones
// 'none' - no data, just timezone API
includeTimezone: 'all'
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
return ENV;
};
and then you can start use tz function and to get abbreviated time zone name you can include z flag in the format.
moment().tz('Asia/Calcutta').format('DD/MM/YYYY h:mm a z')
Related
I have create a mock data and performed a batch update with firestore.batch(). The problem is that location is saved as a number and time as a string and not as Geopoint and Timestamp instances respectively, causing my React app to crash.
I could see that only firestore is accessible through window.firestore, but not Firebase. Since Firebase isn't exported as window.firebase, I cannot create either Geopoint or Timestamp instance.
So, how to create a Timestamp and Geopoint instance in Firebase Emulator from browser console?
Here's a type of doc I'm adding to firestore
const doc = {
"company": "company-1",
"location": [
-72.3623, // number
79.5748 // but, want to convert to Geopoint instance
],
"time": "Fri Sep 10 1976 07:42:23 GMT+0530 (India Standard Time)", // string
"createdAt": "Mon Apr 28 2014 13:30:16 GMT+0530 (India Standard Time)", // want to convert to Timestamp
}
A more dependable accessor path than .Gf:
new firestore.app.firebase_.firestore.GeoPoint(lat, lng)
There's a firebase accessible through window.firestore.
So I figured a way to create Geopoint and Timestamp instance through Firestore.
You can access it through window.firestore.Gf.firebase_, through which you can create those both instance.
const raw = // pasting from clipboard
const batch = firestore.batch()
const firebase = firestore.Gf.firebase_
const Timestamp = firebase.firestore.FieldValue().Timestamp
const GeoPoint = firebase.firestore.FieldValue().GeoPoint
raw.forEach(doc => {
const docRef = firestore
.collection('user')
.doc('user-1')
.collection('interviews')
.doc()
doc = {
...doc,
time: Timestamp.fromDate(new Date(doc.time)),
createdAt: Timestamp.fromDate(new Date(doc.createdAt)),
location: new GeoPoint(doc.location[0], doc.location[1])
}
batch.set(docRef, doc)
})
batch.commit()
I'm using a snapshot test in my project and came across a weird problem when running this specific test on a CI server: it displays the timezone name instead of the GMT code, causing the test failure.
I have tried using "moment-timezone" and Date.UTC() to normalize the dates, the result shown was the correct date with the same issue as above.
I've also tried to stub the global.Date object, but the components complained about prop incompatibility.
it('should render with props', () => {
const order = {
merchant: { logo: 'abc', name: 'Pizza Hut' },
bag: {
items: [{ name: 'Corn & Bacon' }],
total: {
valueWithDiscount: 99.99,
},
},
delivery: {
deliversAt: new Date('2019-05-21 13:00'),
},
payment: {
mode: 'online',
},
lastStatus: API_STATUSES.cancelled,
createdAt: new Date('2019-05-21 12:00'),
details: {},
};
const wrapper = shallowMount(Order, {
...commons,
propsData: { order },
});
expect(wrapper).toMatchSnapshot();
});
See that the expected date is the same as the received one, but syntactic differences:
<div class="order__details">
- <orderdetails-stub paymentmode="online" deliverytime="Fri Jun 21 2019 10:00:00 GMT-0300 (GMT-03:00)" value="99.99" laststatus="cancelled"></orderdetails-stub>
+ <orderdetails-stub paymentmode="online" deliverytime="Fri Jun 21 2019 10:00:00 GMT-0300 (Brasilia Standard Time)" value="99.99" laststatus="cancelled"></orderdetails-stub>
Using Date strings as props like this is hazardous and likely to lead to the sort of problem you're encountering.
Best practice for tests in my experience is to use Date.getTime() so values are numbers of milliseconds without any locale information.
Alternatively, you can use moment-timezone as described in this article:
import moment from 'moment-timezone';
it('renders without crashing', () => {
moment.tz.setDefault('EST');
let props = {
currentDay: moment("2017-09-15 09:30:00").format("MMM Do YYYY h:mm:ss a")
};
const tree = renderer.create(<App {...props} />).toJSON();
expect(tree).toMatchSnapshot();
});
I'm trying to play with asyncData in Nuxt.js and it seems to me that not every property could be placed here as is. For example instances of Moment (moment.js) and DateTime (luxon), they are serialized into string:
import { DateTime } from 'luxon'
const moment = require('moment')
...
asyncData(context) {
return {
date1: moment(),
date2: DateTime.local(),
pureDate: new Date()
}
},
mounted() {
console.log(typeof this.date1) // string ("2019-06-11T16:24:00.746Z")
console.log(typeof this.date2) // string ("2019-06-13T19:24:00.748+03:00")
console.log(typeof this.pureDate) // object (Thu Jun 13 2019 19:24:00 GMT+0300 (Moscow Standard Time))
}
some other complex objects properties raise warn:
Cannot stringify arbitrary non-POJOs OpenPositions
someone please explain me this behavior
sandbox snippet
demo repo on github
I have a DateTimePicker with custom format 'LT'. When I get the value, I get 'YYYY-MM-DD' format instead of ISO-8601.
$('#init').datetimepicker({
format: 'LT',
...
});
var init = $('#init').data("DateTimePicker").viewDate().format();
console.log(init); // Shows 'YYYY-MM-DD' and I want ISO-8601
If I don't format the init variable, I get a moment object with these values:
init {
_ambigTime: true
_ambigZone: true
_d: Wed Mar 20 2019 10:15:00 GMT+0100 (CET)
_f: "YYYY-MM-DD"
_fullCalendar: true
_i: "2019-03-20"
_isAMomentObject: true
_isUTC: true
_isValid: true
... }
I don't know why it has 'YYYY-MM-DD' format declared.
Thanks in advance!
-- EDIT:
I'm using Eonasdan/Bootstrap-DateTimePicker
I tried to cast the init variable with .toISOString() and I still get YYYY-MM-DD format.
It fixed parsing to UTC:
$('#init').data("DateTimePicker").viewDate().utc().format()
I am learning nodeJS now, so I did this tutorial( http://scotch.io/tutorials/javascript/creating-a-single-page-todo-app-with-node-and-angular) , and now I want add timestamp with each todo.
I create a simple file(time.js) with moment.js
var moment = require('moment');
moment().format();
var mytime = moment().format('MMMM Do YYYY, h:mm:ss a');
module.exports = {
time : mytime
}
And connect it to my routes file
var qtime = require('./time');
app.post('/api/todos', function(req, res) {
...
Todo.create({
....
time : qtime.time}
....
Here I get my server startup time, not the time when I POST(thats what I need)
Here the out
"time": "February 21st 2014, 12:00:40 pm",
"time": "February 21st 2014, 12:00:40 pm",
"time": "February 21st 2014, 12:00:40 pm",
...
How to get current time on each request?
There is function that mongoose schema exposes for you that handles default values. These default values can be calculated ones. In this example, the right and easy way to achieve what you ask here is as follows
new Schema({
date: { type: Date, default: Date.now }
})
When you save the object, you do not need to specify the "date" field anymore, mongoose will take care of it!
Mongoose Docs: http://mongoosejs.com/docs/2.7.x/docs/defaults.html (old)
http://mongoosejs.com/docs/schematypes.html (current version)
Why go through all that extra work instead of defining your time field in your schema to be of type Date and use middleware to set?
var todoSchema = mongoose.Schema({
time: Date
});
todoSchema.pre('save', function (next) {
if (!this.isNew) next();
this.time = new Date();
next();
});