Execute formatted time in a slice with html/template - google-app-engine

I'm making this simple webserver that can host my blog, but whatever I do; I can not execute a proper formatted time into my html/template.
Here's what I do:
I've created this struct:
type Blogpost struct {
Title string
Content string
Date time.Time
}
Next up I've created this little func that retrieves the blogposts with corresponding title/dates from the Appengine Datastore and return that as a slice:
func GetBlogs(r *http.Request, max int) []Blogpost {
c := appengine.NewContext(r)
q := datastore.NewQuery("Blogpost").Order("-Date").Limit(max)
bp := make([]Blogpost, 0, max)
q.GetAll(c, &bp)
return bp
}
Finally, in the blogHandler I create a slice based on the retrieved data from the Appengine Datastore using:
blogs := GetBlogs(r, 10)
Now when I Execute my template called blog like this, the dates of the blogs are being parsed as default dates:
blog.Execute(w, blogs) // gives dates like: 2013-09-03 16:06:48 +0000 UTC
So, me, being the Golang n00b that I am, would say that a function like the following would give me the result I want
blogs[0].Date = blogs[0].Date.Format("02-01-2006 15:04:05") // Would return like 03-09-2013 16:06:48, at least when you print the formatted date that is.
However that results in a type conflict ofcourse, which I tried to solve using:
blogs[0].Date, _ = time.Parse("02-01-2006 15:04:05", blogs[0].Date.Format("02-01-2006 15:04:05")) // returns once again: 2013-09-03 16:06:48 +0000 UTC
It is probably some n00b thing I oversaw once again, but I just can't see how I can't override a time.Time Type in a slice or at least print it in the format that I want.

While I looking for a similar functionality to simply format and render a time.Time type in a html/template, I fortuitously discovered that go's template parser allows methods to be called under certain restrictions when rendering a time.Time type.
For example;
type Post struct {
Id int
Title string
CreatedOn time.Time
}
// post is a &Post. in my case, I fetched that from a postgresql
// table which has a datetime column for that field and
// value in db is 2015-04-04 20:51:48
template.Execute(w, post)
and it's possible to use that time in a template like below:
<span>{{ .CreatedOn }}</span>
<!-- Outputs: 2015-04-04 20:51:48 +0000 +0000 -->
<span>{{ .CreatedOn.Format "2006 Jan 02" }}</span>
<!-- Outputs: 2015 Apr 04 -->
<span>{{ .CreatedOn.Format "Jan 02, 2006" }}</span>
<!-- Outputs: Apr 04, 2015 -->
<span>{{.CreatedOn.Format "Jan 02, 2006 15:04:05 UTC" }}</span>
<!-- Outputs: Apr 04, 2015 20:51:48 UTC -->
As a note; my go version is go1.4.2 darwin/amd64
Hope it helps others.

Your Date field has type time.Time. If you format it as a string, and parse it back, you'll once again get a time.Time value, which will still print the default way when the template execution calls its String method, so it's not really solving your problem.
The way to solve it is by providing the template with the formatted time string itself instead of a time value, and you can do that in multiple ways. For example:
Add a method to your blog post type named FormattedDate or similar, which returns a string properly formatted in the style of your preference. That's the easiest, and probably the nicest way if you don't have a fancy use case.
Add a string field to your blog type named FormattedDate or similar; that's very similar to the above option, but you have to be careful to set and update the field whenever necessary, so I'd prefer the method option instead.
If you'd like to format time values in multiple ways within the template, you might also opt to define a template formatter function, so that you might do something like {{post.Date | fdate "02-01-2006 15:04:05"}}. See the documentation on Template.Funcs, the FuncMap type, and this example for details on how to do that.
Update: Sample code for the first option: http://play.golang.org/p/3QYdrDQ1YO

If you output a time.Time in a template it will be converted to a string. This default conversion is what you see. If you need a different format you have two possibilites:
Add a `FormatedDate string field to your Blogpost and populate it from Date via Date.Format(whatever)
Write and register a formatting filter` in your template (see http://golang.org/pkg/html/template/#Template.Funcs) and use this.

Related

How to get raw date string from date picker?

I'm struggling for hours with this seemingly trivial issue.
I have a antd datepicker on my page.
Whenever I choose a date, instead of giving me the date I chose, it gives me a messy moment object, which I can't figure out how to read.
All I want is that when I choose "2020-01-18", it should give me precisely this string that the user chose, regardless of timezone, preferably in ISO format.
This is not a multi-national website. I just need a plain vanilla date so I can send it to the server, store in db, whatever.
Here are some of my trials, so far no luck:
var fltval = e;
if (isMoment(fltval)) {
var dat = fltval.toDate();
//dat.setUTCHours(0)
fltval = dat.toISOString(); // fltval.toISOString(false)
var a = dat.toUTCString();
//var b = dat.toLocaleString()
}
It keeps on moving with a few hours, probably to compensate for some timezone bias
UPDATE 1:
the datestring is data-wise correct. But its not ISO, so I cant use it correctly. I might try to parse this, but I cannot find a way to parse a string to date with a specific format.
UPDATE 2:
I also tried adding the bias manually, but for some reason the bias is 0
var dat = pickerval.toDate()
var bias = Date.prototype.getTimezoneOffset()// this is 0...
var bias2 = dat.getTimezoneOffset()// and this too is 0
var d2 = new Date(dat.getTime()+bias)
var mystring= dat.toISOString() //still wrong
Thanks!
Javascript date functions can be used,
I assume you are getting in 2022-01-03T11:19:07.946Z format then
date.toISOString().slice(0, 10)
to 2022-01-03
There are 2 ways to get the date string:
Use the moment.format api:
date.format("yyyy-MM-DD")
Use the date string that is passed to the onChange as second parameter
Here is a Link.
I am assuming your code snippet is inside the onChange method. This gives you a moment and a date string to work with (the first and second parameters of the function respectively).
You have a few options. You could set the format prop on the DatePicker to match the format of the string you want. Then just use the date string. Or you can use the moment object as Domino987 described.

Angular date filter: Format month as local time

I have a date formatted as a ISO-8601 string: overview.startTime = "2017-05-09T08:00:00Z"
I want to display this on my page and I have used the following code:
Dagens arbetspass {{overview.startTime | date:'dd-MMM'}}
This is displayed as "Dagens arbetspass 09-May". My problem is that this is a Swedish site, and in Sweden we don't start the month names with an uppercase character. Also May is written "maj" (j in the end and not y). I tried to add the timezone like this
Dagens arbetspass {{overview.startTime | date:'dd-MMM':'Europe/Stockholm'}}
but that did not change the output. In fact, most months are spelled differently in Swedish. Any suggestions?
Just use the javascript "toLocaleDateString" method to resolve the concern. The method takes two arguments which are 'locale' and 'options'.
Locale will be "sv-se" for swedish.
Options will provide the format to your string. For example -var options = { weekday: "long", year: "numeric", month:long",day:"numeric" };
var d = new Date("2017-05-09T08:00:00Z");
date.toLocaleDateString("sv-se", options)
Here's a plunker https://plnkr.co/edit/G2IL5Zv0OAcVRMZS9HB7

'date' filter without time zone in angularjs

This is input format:
yyyy:MM:dd'T'HH:mm:ss'Z' (Coming as a string from json service)
Required output format:
dd-mmm-yyyy
I have tried with {{txnDate | date:'dd-mm-yyyy'}}
but it is not working..
What is the format you are following for your date?
A quick var a = new Date(); a.toISOString(); in console will give you something like "2015-02-19T13:30:13.347Z". The formatted string you are receiving is not following any standard and I am afraid parsing it to date will result in Invalid Date in most of the browsers.
So you can either
Get your Date in proper format.
Make the best use of whatever is available. You can use split to break your string into individual components.
Something like:
var a = "yyyy:MM:dd'T'HH:mm:ss'Z'" //Replace with actual string
b=a.split(':') will result in ["yyyy", "MM", "dd'T'HH", "mm", "ss'Z'"] giving you year and months in b[0] and b[1].
For date, you can use b[2].substring(0,2) to give you dd.
You have all date components(apart from time components, which you don't need anyway) as string.
Either use them directly(as a string) or make a date object using these components(since you want month in MMM format).
$scope.txnDate = new Date(b[0]+'/'+b[1]+'/'+b[2].substring(0,2));
I am sure there are more ways to optimize this. Comment if this doesn't work for you, will try to elaborate more.

Angular UI datepicker giving me a UTC converted string. How to parse it back to local time accounting for the time difference?

I am currently running into issues with datepicker automatically converting my time to UTC. Is there anything I can pass into datepicker for it to not give me back a UTC converted string? For example the user picks March 19 on the calendar and the returned string would be something like this
'2014-03-19T04:00:00.000Z'
What I want is ->
'2014-03-19T00:00:00-04:00'
What I am trying now (sort of hacking around it) is trying to use moment js to convert it back to my desired (expected) format, but I am having trouble doing so without hardcoding a subtraction in there. I want to be able to convert it from UTC back to local time.
Does anyone know of a solution to this using moment js or angular?
I ran into the same problem and used a filter that adjusts the date and time using the local data to get around it:
filter('adjustDatepicker', ['$filter', function($filter){
var dateFilter = $filter('date');
return function(dateToFix){
var localDate, localTime, localOffset, adjustedDate;
localDate = new Date(dateToFix);
localTime = localDate.getTime();
localOffset = localDate.getTimezoneOffset() * 60000;
adjustedDate = new Date(localTime + localOffset);
return dateFilter(adjustedDate, 'MM/dd/yyyy');
};
}])
Use it like this in your template file:
{{details.datetomodify | adjustDatepicker}}
I think new Date('2014-03-19T04:00:00.000Z').toString() will give you the local version of the UTC time.

How do I format a string while using a BindingSource?

Technology: Visual Studio 2008 .NET, Winforms
bsTransactions.DataSource = Transactions.Tables[2];
bsnTransactions.BindingSource = bsTransactions;
txtTransOverrideDate.DataBindings.Add("Text", bsTransactions, "TransactionDate", true,DataSourceUpdateMode.Never, "", "MM/dd/yyyy");
Currently, I'm getting an error saying that the string wasn't a recognized DateTime string. Despite the fact that if I get the column type from
Transactions.Tables[2].Rows[0]["TransactionDate"].DataType.ToString();
returns "System.DateTime" and the actual value looks like "1/23/2010 12:00:00 AM"
I'm trying to format a string that currently looks like "1/23/2010 12:00:00 AM" to only show the date.
The catch is, there's a BindingSourceNavigator being use, so just applying the formatting to the textbox after the fact only applies to the first value, but not any others that are navigated to using the bindingNavigator.
I have a feeling that using the "bsTransactions" to applies bindings to the textbox, it's changing the datatype, hence it not being recognized as a DateTime.
txtTransOverrideDate.DataBindings.Add("Text", bsTransactions, "TransactionDate", true,DataSourceUpdateMode.Never, "", "MM/dd/yyyy");
I made changes in the original post to mimic this, but this is the answer.

Resources