Date.Format for javascript date - javascript

I have an array of
struct {
Date time.Time
PostedSample int
}
loaded from the appengine datastore which I want to output in a html/template for the Google Visualization Time Line. First I tried formatting the Date directly in the template with {{.Date.Format "new Date(2006,1,2,15,4,5)"}} but html/template escapes this so it appears as a quoted string in the html source. I then tried formatting the date into a []struct{Date template.JS; Value template.JS} with the expression template.JS(m.Date.Format("new Date(2006,1,2,15,4,5)")) which almost works except the month is off by one, javascript wants January as 0. I could have the template generate a json of date parameters and write javascript turn that into Date objects or have go code which adjusts the template output. Please share a more elegant solution. Thank you.

You don't need to add a format function to the templates.
You can use your struct like so:
{{.Date.Format "Mon 2 Jan 2006"}}
The solution might be something like this:
var date = new Date(parseInt({{.Date.Nanosecond }} /1000));

Related

Vue JS - Retrieve date only

I'm making an api call which retrieves a set of objects. One of the objects returns a date and time together like this:
createdAt: "2020-11-04 09:48:32"
This is where I display the date and time:
<template v-for="item in collectedTrash">
<BeforeAndAfter v-if="item.isPresented === 1"
:key="item.username"
:avatarUrl="require('#/assets/img/images/img_stats_km#2x.png')"
:imageBefore="getImageUrl(item.imageUrlBefore)"
:imageAfter="getImageUrl(item.imageUrlBefore)"
:username="item.username"
:date="item.createdAt"/> This is where I get the date
</template>
Is there anyway that I can retrieve the date only, rather than the date and time?
I am assuming you don't have access to the api and therefore have to process the date in your vue application.
Do you need the date as a date Object or is a string fine?
If a string representation is enough, you could use a library such as Date fns and use the format function:
...
:date="format(new Date(item.createdAt), 'yyyy-MM-dd')"
Another option might be to only use the first 10 characters of the string you received as the date: date="item.createdAt.substring(0,9)"
Did you try something like: :date="item.createdAt.substr(0, 10)"
In my experience the easiest way to format datetimes in JS it to use the Moment.js library (https://momentjs.com/). You could reformat the datetime string before passing it to your child component.
Or, if you don't want to rely on a third-party library and you know that the datetime string will always be passed in that format, I suppose you could do item.createdAt.slice(0, 10).
Moment.js can be very helpful with dates and times
Moment Docs
moment("String").format('L'); // 04/11/2020

Detect if string is a Date with an exact given format

I'd like to check whether a string does represent a Date with an given format.
I tried Date.parse(string, format) but it parses the string to date even if it's in a whole different format. E.g.:
Date.parse("2015-07-04T23:10:00.000+02:00", "yyyy-MM-ddTHH:mm:ss.SSSZ") // Parsed as a date
Date.parse("2000", "yyyy-MM-ddTHH:mm:ss.SSSZ") // Parsed as a date also`
I don't want to parse the second row as a date, because its not in the required format.
I also tried Date.parseExact() method of Date.js but it didn't parsed the date if I provided a timezone and a format like above.
The right solution was based on RobG's comment: (but thanks to everyone for helping me)
moment("2015-07-04T23:10:00.000+02:00", "yyyy-MM-ddTHH:mm:ss.SSSZ", true).isValid()
Every other solution succeeded the parsing even if the input was only a year which I tried to avoid. The last parameter "true" stands for the "strict" parsing which provides exactly the output that I was looking for.
You can leverage MomentJS and its function .format()
How does it work? here is the documentation, it's fairly simple, you wanna use your string in combination with the format string.
MomentJS .format()
And here is the quick demo Fiddle:
var myString = "2015-07-04T23:10:00.000+02:00";
var formatString = "yyyy-MM-ddTHH:mm:ss.SSSZ";
if (moment(myString, formatString)._i == myString) console.log("GOOD");
1-liner with momentJS
I basically format your string in targeted format then check if the result matches your string.
Worth noting is that MomentJS is (IMHO) the best date and time lib for JS. I never found a reason to venture beyond it since I discovered it, after using some of the less capable libs in the past.
If you don't wanna use lib, making a regex to suit your needs is a viable alternative of similar length.
Altho, if you intend to work with a lot of dates/times, MomentJS is still a way to go as it offers so many useful things which cannot be done by regexes alone.
Why not use regular expression to check if input matches the format and parse it if it does?
reg=new RegExp(/[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}\:[0-9]{2}\:[0-9]{2}\.[0-9]{3}\+[0-9]{2}\:[0-9]{2}/);
str="2015-07-04T23:10:00.000+02:00";
date=new Date(str);
if(str.match(reg) && date.toString()!='Invalid Date')
{
Date.parse(str);
}
Edited to add date check.

Parse this value with moment doesn't work

I have a date value like this value.game_date = 2013-10-27 03:39:35 and I'm trying to parse it as follow:
moment().format(value.game_date, 'DD-MM-YYYY');
But I get this as result 29-10-2013 00:00:00 where I'm looking for this format: 29-10-10-29 without hour, what I'm doing wrong?
I think you have some typos or misinformation in your post regarding the output you're getting and what you're desiring.
Based on what appears to be a misunderstanding of moment, however, I am pretty sure that what you want is:
value.game_date = '2013-10-27 03:39:35';
var formatted_game_date = moment(value.game_date).format('DD-MM-YYYY');
// produces '27-10-2013'
moment() is a factory function which takes a date string and returns a moment instance. That moment instance then has various methods available, such as format() which takes a format string as the first param.
So your code is producing a moment instance representing current date/time (because you're not passing any params to moment()), then you ask .format() to return a string formatted using your date stamp as the formatter. Your date string doesn't have any of the things in it which format would parse and replace, so you just get back your date string.
The code I gave passes the date string to moment to produce the instance, then asks .format() for a formatted string using your desired format template.

How to parse date time in JavaScript

I have Date in this format mm/dd/yy example: 04/11/13
and time in the format HH:MM:SS example: 17:02:30
I have to parse above two values and put in a variable dateTime with following format
YYYY-MM-DDTHH:MM:SSS
2013-04-11T17:02:30.000
What is best way to do it in AngularJS or in Javascript. I also need to verify the user input and make sure it is a valid mm/dd/yy date and a valid HH:MM:SS time
I know there are tons of duplicate/similar questions but I couldn't find one which answers above, please let me know if you found one.
You don't need an external library to do this. See this doc link for the forms of date that JavaScript can process normally.
For a specific solution to your question:
var date = new Date("04/11/13" + " " + "17:02:30");
date.toISOString();
>> "2013-04-11T21:02:30.000Z"
See this MDN page for more info on the Date object.
The best way to do this in AngularJS is with a filter. You bind to the dateTime, and then filter it with the date filter.
<span>{{myDate | date:yyyy-MM-ddThh:mm:sss}}</span>
Or in your controller you say:
$filter('date')(date[, format])
Here is more info: http://docs.angularjs.org/api/ng.filter:date

Proper way to format date from database using javascript/jquery

I am calling my database which contains a datetime datatype. The date looks like this:
2005-05-23 16:06:00.000
I would like to display this in a table when a user selects a certain item from a list. I call my controller action and return Json of all the times and put them in a table. The problem is the date is completely wrong. What is displayed is this:
/Date(1255470180000)/
The date that is returned isn't even parsable (which I don't want to do anyway) so I can't even get the data if I wanted to. Any ideas?
The date you're getting back is serialized to a marker and a number of milliseconds since midnight 1st Jan 1970 (in UTC). If you isolate the numeric portion, convert it into a number, and feed it into the Date constructor you'll get an actual date to work with, which you can then format as you like.
var ticks, dt;
// Isolate the numeric portion of the value
ticks = /[0-9]+/.exec(json.dateValue)[0];
// Convert to a number
ticks = parseInt(ticks);
// Convert to a date
dt = new Date(ticks);
Alternately, if the JSON serializer on the server supports a "replacer" parameter as Crockford's and ECMAScript 5th edition's do, you could supply a replacer that formatted the date into a string server-side and handle it there, since you said you don't want to parse the date client-side (although the jQuery tag suggested to me maybe you did).
The other alternative is to return the formatted string from the controller action. You could even leave the timestamp and return a second field as "Formatted Timestamp" or something similar.
var listFromDb = ...
return new Json(listFromDb.Select(itemFromDb => new List { new
{ Date = itemFromDb.Date, FormattedDate = FormatDate(itemFromDb.Date), ...}
I ended up formatting the code in the controller action instead.
I just cast the datetime property to a string using .ToString() and got the desired results.
Thanks for the help though guys.

Categories