MomentJS how to get formatted, but not localised representation? - javascript

I'm using MomentJS v2.8.4, and I'm trying to get formatted date like "31/12/2015"
myDate.format('DD/MM/YYYY') works fine until I set some "less English :)" localisation, e.g. Arabic. Then I get something like this ١٠/٠١/٢٠١٥, which is nice for the user, not so nice for API.
From MomentJS source code
format : function (inputString) {
var output = formatMoment(this, inputString || moment.defaultFormat);
// here I get correct "31/12/2015" format
return this.localeData().postformat(output); // this will return localized version
},
formatMoment function is not publicly exported...
Can you please suggest correct solution for this?

You could save the current locale() setting in a variable (i.e save the user's setting) and then explicitly set the locale value so that you can get your date format correct for your API call, then set the locale value back to the saved value.
Something like:
var userLocaleSetting = moment.locale();
moment.locale('en');
var myFormattedDate = myDate.format('DD/MM/YYYY');
moment.locale( userLocaleSetting );

One solution may be to return an object with the api and user formatted date.
format : function (inputString) {
var api = formatMoment(this, inputString || moment.defaultFormat);
// here I get correct "31/12/2015" format
var user = this.localeData().postformat(api); // this will return localized version
return {api: api, user: user};
},

Related

Cannot get Date format using getDateTimeInstance function

I have a requirement that I need to adjust the date inside the worklist view, based on the date format set in frontend system (in GUI).
My code for formatter.js file:
DatePriority: function (sVar1, sVar2) {
var oDateFormat;
var oDateFormatFromGUI = sap.ui.getCore().getConfiguration().getFormatSettings().getDatePattern("short");
oDateFormat = sap.ui.core.format.DateFormat.getDateTimeInstance({
pattern: "EEE " + oDateFormatFromGUI,
UTC: true
});
return oDateFormat.format(new Date(sVar1));
}
However, oDateFormatFromGUI sometimes does return value, but sometimes it is undefined.
Is there a specific reason for this behavior? How can I make sure that oDateFormatFromGUI always has the data? Is it because I define it in formatter file, and not at the controller level?
Thank you.

How to get Timezone by passing abbreviation?

I'm using Momentjs and as of now i'm getting date and time by doing the following steps
var TimeZone = moment.tz("Asia/Kolkata").format('LLLL');
but i need to get time and date by passing abbreviation for instance
var TimeZone = moment.tz("IST").format('LLLL');
How can i achieve this?
I don't know Momentjs but I can provide u JS solution to do the same thing.
As i have understood from ur problem that ".tz" method only accepts full time zone name instead of short form. So u can use JS prototypal inheritance to achieve this outcome.
What u have to do is make another method of ur own with a dictionary object and extend "moment" object with ur features. Refer the code:
var tzMap = {
"IST" : "Asia/Kolkata",
"UST" : "America/LA" // this I only took for example i don't know it exist
or not
}
moment.__proto__.timezone = function(tzStr){
if(Object.hasOwnProperty(tzStr)){
tzStr = tzMap[tzStr];
}
return this.tz(tzStr);
}
// now instead of using
// moment.tz("Asia/Kolkata").format('LLLL');
// U can use
var TimeZone = moment.timezone("Asia/Kolkata").format('LLLL');
// or
var TimeZone = moment.timezone("IST").format('LLLL');

How to parse a Javascript datetime to C# DateTime parameter

According to my previous question here: How to send a JSON object using GET method, I could retrieve my values because the object is no longer null. My object contains one DateTime property called CreatedOn. I am sending the value from javascript as new Date(). Before to answer that I can get the DateTime.Now() from code-behind, there is a purpose to send the date from HTML.
Then, in debug mode when I arrive to the controller method, my CreatedOn property is always DateTime.MinValue = 01/01/0001 12:00:00 AM
I changed my javascript value to this format "yyyyMMddT000000" because I thought that this would be parsed automatically but I didn't have any success.
How can I do to send the value that can be parsed by the web api2 controller automatically?
<script>
$("#btnTest").on("click", function () {
var searchCriteria = {};
searchCriteria.ID = 0;
searchCriteria.Name = "";
//1. First tried option
//searchCriteria.CreatedOn = new Date();
//2. Second tried option. Test
searchCriteria.CreatedOn = "20170324T000000";
var url = "http://localhost:8080/api/products"
$.getJSON(url, searchCriteria).done(processResponse);
});
function processResponse(response){
}
</script>
I got it. Hope this can help others.
searchCriteria.CreatedOn = new Date().toISOString();
This will be parsed automatically.
Cheers.

How can I get date and time separately using jQuery?

In my table date is listed as "2015-07-31 06:02:20". How can I get date and time separately using jQuery?
I used some code but it shows some errors.
var timestamp = new Date(data.responsecusthistory.created_at);
var date = timestamp.toDateString();
Error: Invalid Date
var date = data.responsecusthistory.created_at.split(" ")[0];
var time = data.responsecusthistory.created_at.split(" ")[1];
If you want to have a time string (i.e. HH:MM:SS), try e.g. this:
var timestampTime = timestamp.toTimeString().split(' ')[0];
Anyway, there's no obvious reason why you get the "Error: Invalid Date", as long as
data.responsecusthistory.created_at
is a correct value, such as "2015-07-31 06:02:20". Please consider double-checking this variable.
Try this:
dateString= "2015-07-31 06:02:20";
temp = new Date(dateString);
dateStr= $.datepicker.formatDate('mm/dd/yy', temp );
for getting different formats check the link https://github.com/phstc/jquery-dateFormat.
Using different formats we will get different date, time etc in which ever forms we need it.

Deserializing JSON dates timezone-less

I have a problem that is breaking my head since yesterday and don't know how to deal with it.
I have a date field in my database that contains the following value:
Then my application get the value and send that to my web form. (the value still the same :) thats fine!!
In client side I put a break with a javascript alert to see the value that is comming from JSON (the value still the same :) thats fine!!
The code in client side for the alert is this:
// transaction json model
var jsonTransaction = #(Html.Raw(Json.Encode(this.Model.Transaction)));
alert(new Date(parseInt(jsonTransaction.Date.substr(6))));
Now when I send back the value to the server this is what I get
And finally after deserialization of the JSON my date time is wrong!! instead of Day 7 its now Day 8???????
This is the code for deserializing:
public JsonResult SaveBill(string jsonTransaction, string jsonTranDetails)
{
_appState = this.AppState;
JsonResult returnVal = returnVal = Json(
new { Success = true }
);
var transaction = JsonConvert.DeserializeObject<BillTransaction>(jsonTransaction, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
Any clue on how to solve this issue with dates, I should get the same date because I didn't change anything. Hope someone can guide me for a solution.
Thanks in advance.
Java script use universal time when it parse the date as currentdate = new Date(123232)
so when you send date to client convert it to ISO date such as
make sure the date is in UTC before convering it to strong .
return String.Format("{0:yyyy-MM-ddTHH:mm:ss.fffZ}", dt);
bty I already created JSON Converted to override any date serialization to client side to use the above function .

Categories

Resources