I have a datepicker on my page, when I select any date it produced a result something like
Sun Sep 07 2014 00:00:00 GMT+0500 (Pakistan Standard Time)
And I need to format it: YYYY-MM-DDTHH:mm:ss Z
So, for this I use moment syntax
var date='Sun Sep 07 2014 00:00:00 GMT+0500 (Pakistan Standard Time)';
moment(date).format('YYYY-MM-DDTHH:mm:ss Z');
which produces an output
2014-09-07T00:00:00 +05:00
That's good, but my api expect standard timezone offset 'Z' instead of parsing into local current time zone (i.e +5:00) in my case.
So, I want to produce this
2014-09-07T00:00:00Z
How is it possible?
Use moment.utc() to display time in UTC time instead of local time:
var dateValue = moment(date).utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z';
or moment().toISOString() to display a string in ISO format (format: YYYY-MM-DDTHH:mm:ss.sssZ, the timezone is always UTC):
var dateValue = moment(date).toISOString();
JSFiddle
Rather than using a hard-coded format string and then concatenating the 'Z' after it, it would be better to just use the toJSON() function which has been around since moment js v2.0. Like so:
moment('Sun Sep 07 2014 00:00:00 GMT+0500 (Pakistan Standard Time)').toJSON();
Here's the complete JSFiddle.
Related
I'd like to have millisecond precision for my logging in my golang project, currently using log15 library
Problem is when I append it to Context, it rounds back up to seconds
newTimeWithMilliseconds := time.Unix(0, time.Now().UnixNano())
return log.FuncHandler(func(r *log.Record) {
r.Ctx = append(r.Ctx, "time", newTimeWithMilliseconds)
nextHandler.Log(r)
})
When I convert it to string newTimeWithMilliseconds.String() it works and I get "2018-09-25 15:07:45.25801232 -0500 PDT", but when I don't, the decimals go away and I get 2018-09-25 15:07:45 -0700 PDT.
I want to keep in Time format though and not use string, anybody have any ideas on why this is happening and how to solve this?
You need to use time.Format to display your time.Time's value with the precision you want. It doesn't loose its precision unless you modify its value, the reason why you see a difference is only due to the layout used by the call for time.Format of whatever is printing your time.
When you use mytime.String(), the layout used is different that the one used by whatever prints your time otherwise.
That's why you need to either use the time.Time value but manipulate the way it is printed, or store it as a formatted string instead.
See Go by example
// Go supports time formatting and parsing via
// pattern-based layouts.
package main
import "fmt"
import "time"
func main() {
p := fmt.Println
// Here's a basic example of formatting a time
// according to RFC3339, using the corresponding layout
// constant.
t := time.Now()
p(t.Format(time.RFC3339))
// Time parsing uses the same layout values as `Format`.
t1, e := time.Parse(
time.RFC3339,
"2012-11-01T22:08:41+00:00")
p(t1)
// `Format` and `Parse` use example-based layouts. Usually
// you'll use a constant from `time` for these layouts, but
// you can also supply custom layouts. Layouts must use the
// reference time `Mon Jan 2 15:04:05 MST 2006` to show the
// pattern with which to format/parse a given time/string.
// The example time must be exactly as shown: the year 2006,
// 15 for the hour, Monday for the day of the week, etc.
p(t.Format("3:04PM"))
p(t.Format("Mon Jan _2 15:04:05 2006"))
p(t.Format("2006-01-02T15:04:05.999999-07:00"))
form := "3 04 PM"
t2, e := time.Parse(form, "8 41 PM")
p(t2)
// For purely numeric representations you can also
// use standard string formatting with the extracted
// components of the time value.
fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
// `Parse` will return an error on malformed input
// explaining the parsing problem.
ansic := "Mon Jan _2 15:04:05 2006"
_, e = time.Parse(ansic, "8:41PM")
p(e)
}
Outputs
2009-11-10T23:00:00Z
2012-11-01 22:08:41 +0000 UTC
11:00PM
Tue Nov 10 23:00:00 2009
2009-11-10T23:00:00+00:00
0000-01-01 20:41:00 +0000 UTC
2009-11-10T23:00:00-00:00
parsing time "8:41PM" as "Mon Jan _2 15:04:05 2006": cannot parse "8:41PM" as "Mon"
Try it out yourself here
I want to display the local time from an ISO 8601 string using momentjs.
There is a discrepancy of minutes when I convert an ISO string using different date formats. If I use 'MM/DD/YYYY HH:mm', the minutes is correctly displayed. If I use 'ddd, MMM Do HH:MMa', 11 minutes is added (in my case).
My sample js (babel) code:
let today = moment('11/09/2016 00:00', 'MM/DD/YYYY HH:mm').toISOString();
//today = 2016-11-09T08:00:00.000Z
let formatted = moment(today, moment.ISO_8601).format('MM/DD/YYYY HH:mm');
//formatted = 11/09/2016 00:00
let formatted2 = moment(today, moment.ISO_8601).format('ddd, MMM Do HH:MMa');
//formatted2 = Wed, Nov 9th 00:11am
I would prefer using the second format. Can someone explain why there is a discrepancy?
Please see this fiddle: https://jsfiddle.net/anudhagat/8fgtjbc7/3/
I caught my silly mistake. I have capitalized the minutes in the second format, using MM makes it display months instead of minutes.
I have a date like "Thu Sep 01 2016 00:00:00 GMT+0530 (IST)" which I need to send to server as ISO-8601 utc time. I tried like :
moment(mydate).toISOString()
moment.utc(mydate).toISOString()
moment(mydate).utcOffset("+00:00").toISOString()
but I am getting the result like
2016-08-31T18:30:00.000Z
which is 1day behind my intended time. So what can I do to make moment ignore my local timezone and see it as UTC?
Edit:
The expected output is
2016-09-01T18:30:00.000Z
And no, the initial input isn't a string rather a javascript "new Date()" value.
Reason this happens:
This happens because .toISOString() returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString()
Solution:
Use the same function and pass true value to it. This will prevent UTC Conversion.
moment(date).toISOString(true)
const date = new Date("2020-12-17T03:24:00");
const dateISOStringUTC = moment(date).toISOString();
const dateISOString = moment(date).toISOString(true);
console.log("Converted to UTC:" + dateISOStringUTC)
console.log("Actual Date value:" + dateISOString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I take the same problem today and find the solution.
Here is the solution: moment(date,moment.ISO_8601)
var date = new Date();
console.log("Original Date");
console.log(date);
console.log("After Moment Format");
console.log(moment(date,moment.ISO_8601));
Test Execution:
Moment Documentation: MomentJs
I am trying to parse two date strings into date objects. The code works for one string, but throws an "invalid date time" error for the other. The only difference is that it's got a "Sat, " at the beginning! Please tell me why this is happening and how I can solve it!
<cfset datetimetest1 = "23 Nov 2013 00:53:12 +0000">
<!--- ^ This throws an error (when you try to pass it). Error says 'invalid date time' --->
<cfset datetimetest2 = "Sat, 23 Nov 2013 00:53:12 +0000">
<!--- ^ This works when it is parsed --->
<cfoutput>
#parsedatetime(datetimetest1)# #parsedatetime(datetimetest2)#
</cfoutput>
I identified RSS dates that are being used from the following sources and tested them against isDate(), DateFormat() and LSDateFormat(). ColdFusion 10,286680 was only able to parse 65% of the dates (38 out of 58).
http://rssdateformats.tumblr.com/
https://github.com/mjibson/goread/blob/0387db10bd9fd9ccd90d557fa30b6e494efa577a/goapp/utils.go#L129
Here's the test script that I wrote:
https://gist.github.com/JamoCA/7617349
I've been looking for a Java date parser library and recently found Natty and StringToTime, but haven't used either yet. (Neither resource provides a downloadable JAR file.):
http://natty.joestelmach.com/
https://github.com/collegeman/stringtotime
Update:
As of CF10+, you can use a custom format string to instruct the function on how to parse and convert the input into a datetime object:
// Custom format string
dateObject = parseDateTime("23 Nov 2013 00:53:12 +0000"
, "dd MMM yyyy HH:mm:ss zzz");
This is one area in which CF's flexibility and ease of use can be a disadvantage IMO. Unfortunately parseDateTime does not allow you specify the format of the input string, so CF has to do a lot of guessing to "automagically" convert your string into a date object.
One of the tools CF employs is java's SimpleDateFormat class, which utilizes patterns to parse or convert strings into Dates. My understanding is CF maintains a listing of standard date/time patterns (according to U.S. date conventions). Your first string must not match any of those patterns. Hence the error.
If your date strings are always in UTC, you could simply use list functions to omit the timezone offset ie +0000, then parse the string as usual:
<cfscript>
origString = "23 Nov 2013 00:53:12 +0000";
dateString = listFirst(origString, "+");
WriteDump(parseDateTime(dateString));
</cfscript>
Or you could DIY using SimpleDateFormat and the appropriate pattern dd MMM yyyy HH:mm:ss Z (see Date and Time Patterns). Just note the returned dates are in local time, so you may need to use DateConvert if you want UTC times:
// get formatter based on default locale
formatter = createObject("java", "java.text.SimpleDateFormat").init();
// set up pattern for input date string
formatter.applyPattern("dd MMM yyyy HH:mm:ss Z");
// parse it into a date object
dateObject = formatter.parse("23 Nov 2013 00:53:12 +0000");
// display result in local and UTC time
WriteDump("local="& dateObject);
WriteDump("utc="& DateConvert("local2UTC", dateObject));
Why cannot IE parse this string as a Date object.
var d = Date.parse("Fri Jun 11 04:55:12 +0000 2010"); // returns NaN
However, it works well in FireFox. I am running IE 8.
Thanks.
You are getting NaN value in IE 8 and its working in Firefox because the format of the string varies with browser and operating system.
For example, in IE6 for Windows XP, the string is in the following format:
Tue Dec 05 16:47:20 CDT 2006
But in Firefox for Windows XP, the string is
Tue Dec 05 2006 16:47:20 GMT-0500
to make it compatible with both browser you will have to first check the browser in your
javascript code and then accordingly give your input date string.
I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.
You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:
$.datepicker.parseDate('yy-mm-dd', '2007-01-26');
Is solved my problem by creating an date object and let me give it back the timestamp.
But for this you need to convert you string into this format:
year, month, date, hours, minutes, seconds,ms
an example would be like:
dateObj = new Date(year, month, date);
timestamp = dateObj.getTime();
This works save in IE and FF.
IE Dev Center: Date Object (JavaScript)
Mozilla Dev Network: Date
For your example you would to something like this:
//your string
var str = "Fri Jun 11 04:55:12 +0000 2010";
//maps months to integer from 0 to 11
var monthArray = {"Jan":0, "Feb":1, "Mar":2, "Apr":3, "May":4, "Jun":5, "Jul":6, "Aug":7, "Sep":8, "Oct":9, "Nev":10, "Dec":11};
//get the values from the string
var regex = /^[^ ]+ ([^ ]+) (\d{1,2}) (\d{2}):(\d{2}):(\d{2}) \+(\d{4}) (\d{4})$/;
match = regex.exec(str);
var month = monthArray[match[1]],
date = match[2],
hours = match[3],
minutes = match[4],
seconds = match[5],
ms = match[6],
year = match[7];
//create date object with values
var dateObject = new Date(year, month, date, hours, minutes , seconds, ms);
var ts = dateObject.getTime(); //timestamp in ms
Problem
In case your date is stored in SQL datetime like 2020-04-07 05:30:00 and want to parse it in IE. When you parse it with JavaScript in IE using new Date(), it outputs Invalid Date while latest versions of Chrome and Firefox parse this date correctly.
Solution
You have to replace <space> with T in datetime string coming from SQL.
Example
let myDate = '2020-04-07 05:30:00';
let myFormattedDate = myDate.replace(' ', 'T'); // '2020-04-07T05:30:00'
console.log(new Date(myFormattedDate));
because of the +00000. try to add that the last
var d = Date.parse("Fri Jun 11 04:55:12 2010 +0000");
This may help you. I just solved a problem similar to this.
Problem with Javascript Date function in IE 7, returns NaN