moment js displays milliseconds after AM/PM - javascript

Currently working on a project that deals with different languages and ran into a weird behavior when displaying milliseconds in the PM/AM format.
If I want to display a date/time pair with millisecond precision using the AM/PM format I get something like this:
12/14/2017 3:45:45 PM.199
Whereas the same date/time in a 24h format is shown like this:
12/14/2017 15:45:45.199
Is there a way to display the AM/PM format like this:
12/14/2017 3:45:45.199 PM
The objective is to dislpay the date/time according to the users localization options, that is why I'm using the "L LTS" formatting.
Here is a fiddle to illustrate the problem
var divEn = $('#divEn');
var divFi = $('#divFi');
var en = "en";
var pt = "pt";
var dateEn = moment().locale(en);
var dateFi = moment().locale(pt);
format = "L LTS.SSS";
divEn.text(dateEn.format(format));
divFi.text(dateFi.format(format));

If you always want to display result like 12/14/2017 3:45:45.199 PM use MM/DD/YYYY h:mm:ss.SSS A as format token instead of L LTS.SSS.
MM stands for number of month, DD is day of the month, YYYY is the year, h is the hour (0..12), mm stands for minutes, ss stands for seconds, SSS stands for fractional second and A stands for AM/PM.
L and LTS are localized tokens (output varies based on locale).
EDIT:
You can use localeData() and longDateFormat() go get localized format token, then you can check if the LTS token contains the AM/PM token (A or a) and change the format dinamically.
Here a live sample:
function getCustomLocalizedFormat(locale){
var localeData = moment.localeData(locale);
var lts = localeData.longDateFormat('LTS');
var format = "L LTS.SSS";
if( lts.match(/a/i) ){
format = "L h:mm:ss.SSS A";
}
return format;
}
var divEn = $('#divEn');
var divFi = $('#divFi');
var divRes = $('#divRes');
var en = "en";
var pt = "pt";
var dateEn = moment().locale(en);
var dateFi = moment().locale(pt);
var enLocaleData = moment.localeData('en');
var formatEn = getCustomLocalizedFormat('en');
var formatPt = getCustomLocalizedFormat('pt');
divEn.text(dateEn.format(formatEn));
divFi.text(dateFi.format(formatPt));
divRes.text(moment().format('MM/DD/YYYY h:mm:ss.SSS A'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment-with-locales.min.js"></script>
<p>English</p>
<div id="divEn"></div>
<p>Portuguese</p>
<div id="divFi"></div>
<p>General</p>
<div id="divRes"></div>
Please note that:
This approach is not test for each locale supported by momentjs. Locales like pa-in(Punjabi), ml (Malayalam), ne (Nepalese), hi (Hindi), gom-latn (Konkani Latin script) and others have the LTS token that starts with A. It's not clear to me what is the your expected output for these locales.
You can customize Long Date Formats using updateLocale function and the longDateFormat key.
Probably the best approach is to define a subset of supported locales and define custom format for each locale (and/or just customized moment's LTS).

Related

How to format a Date in a Specific Format in React.js?

I want to show the full date formatted from this 2020-11-09T17:50:00.000Z
to this 22/1/2020 14:20:22 format. I know how get the desired format via moment.js, but want to achieve this with JavaScript Date.
Here is what I have now, but this is not what I want.
let d = new Date("2020-11-09T17:50:00.000Z".toLocaleString("en-US"))
console.log(d);
Any help will be appreciated
You can always do it manually, the Date API only has a limited set of functions like .toLocaleDateString() which will give you "11/9/2020" and .toGMTString() will return "Mon, 09 Nov 2020 17:50:00 GMT".
Using your Date APIs, you can build the string yourself using what you have.
var timeString = d.toGMTString().split(" ")[4]; //This will return your 17:50:00
//For the date string part of it
var dateNumber = d.getDate();
var monthNumber = d.getMonth() + 1;
var yearNumber = d.getFullYear();
var dateString = `${dateNumber}/${monthNumber}/${yearNumber}`;
var finalDateString = [dateString, timeString].join(" ");
toLocaleString() can produce many formats, and you can choose the locale to get the format (or close to it) that you want.
The locale "en-GB" gives you almost what you want; you just need to remove the comma that it puts in...
let d = new Date(2020, 0, 22, 14, 20, 22);
let output = d.toLocaleString("en-GB")
.replace(',' ,'');
console.log(output);
You can actually control the output further by using the options parameter.
But also see the Intl object for its DateTimeFormat constructor.

What is the difference in these timestamps?

So I am trying to make a post request to an API, and one of the values required is a date that according to there documentation should be in the following format
Start time of the timesheet, in ISO 8601 format
(YYYY-MM-DDThh:mm:ss±hh:mm). Time should reflect the user's local time.
But when I try to make a new Date().toISOString() value in the ISO format I get this
2019-07-17T19:50:08.057Z
So I guess my question is, how can I produce the supposed format that they are looking for which is apparently a different ISO 8601 format? Or what would be the format for the following timestamp?
2018-07-25T13:10:23-07:00
here is the documentation to the api that I am playing around with https://tsheetsteam.github.io/api_docs/#create-timesheets
Your question is similar to Javascript date format like ISO but local but you want the timezone also, so:
function toISOLocal(date) {
// Pad single digit numbers with leading zero
function z(n){return (n<10?'0':'')+n}
// Copy the input date
var d = new Date(date);
// Get offset and adjust
var offset = d.getTimezoneOffset();
d.setMinutes(d.getMinutes() - offset);
// Build timestamp with adjusted date and local offset
var sign = offset < 0? '+' : '-';
offset = Math.abs(offset);
var offsetStr = sign + z(offset/60|0) + ':' + z(offset%60);
return d.toISOString().replace(/z$/i, offsetStr);
}
console.log(toISOLocal(new Date()));
However I suspect you can get by with the built–in toISOString and just replace the trailing Z with +00:00. You might need to remove the decimal seconds part also:
function modifyISO(d) {
return d.toISOString().replace(/\.\d+/, '').replace(/z$/i,'+00:00');
}
console.log(modifyISO(new Date()));
Just remove the tail. Something like this.
console.log(new Date().toISOString().replace(/(.+)(\..+?$)/g,'$1'));
You need set location time to make reference to meridian 0 + or - , you can set with library like momentjs, basically you set a reference to compare
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00

How to convert windows SYSTEMTIME to Unix with JavaScript?

I receive a date as a string of 18 numbers such (Example: "636664860000000000") from an API that uses .NET.
Based on my research, it is a windows SYSTEMTIME format value that needs to be converted to FILETIME then UTC. I am unable to find a way to do this other than through the back end itself.
Is there a way to convert this number to a UTC time stamp with JavaScript?
Give this a try: https://plnkr.co/edit/GXTO1gigMAbumRU643KB?p=preview
function convert(){
var winTicks = 10000000;
var uEpoch = 11644473600;
var time = document.getElementById('filetime').value;
var unixTime = time/winTicks - uEpoch;
console.log(unixTime);
var utc = new Date(unixTime * 1000).toUTCString();
var label = document.getElementById('utctime');
label.innerHTML = utc;
}
And compare with this tool: https://www.epochconverter.com/ldap

How to set Date formate in javascript?

I want to convert datetime format for my radtime picker. I am getting 2012-8-2-13-00-00
as my output when I pick date from my radtime picker. When I try to convert in to date it is saying invalid date.
The JavaScript:
function SourqtyValidation()
{
var specifiedtime = document.getElementById('<%=txtSpecifiedArrvialTime.ClientID %>').value;
alert(specifiedtime);
var a = new Date(specifiedtime);
var actuvalarrivaltime = document.getElementById('<%=txtActualArrivalTime.ClientID %>').value;
alert(actuvalarrivaltime);
var b = new Date(actuvalarrivaltime);
b.format("dd/MM/yyyy hh:mm:ss");
alert(b);
var difference =Math.round((a - b) / 1000);
alert(difference);
}
The aspx:
//txtSpecifiedArrvialTime = predifened as 2012/08/02 09:35:55;
<telerik:RadTimePicker ID="txtActualArrivalTime" runat="server" EmptyMessage="Actual Arrival Time"> </telerik:RadTimePicker>
So how can I get difference between two times in minutes?
to get the time difference,date should be in same format,
"2012-8-2-13-00-00" is not the correct format, convert it into format of "2012/08/02 13:00:00"
than you can get the differencein in second by dividing it to 1000.
you can use this to convert your string to datetime
var dt = '2012-8-2-13-00-00'.split(/\-|\s/);
dat = new Date(dt.slice(0,3).reverse().join('/')+' '+dt[3]+':'+dt[4]+':'+dt[5]);
Try using Datejs it has very handy methods:
Eg.:
Date.parse('Thu, 1 July 2004 22:30:00');
Date.parseExact("10/15/2004", "M/d/yyyy"); // The Date of 15-Oct-2004
Very Good library for handling Data Time in javascript.
Datejs is an open-source JavaScript Date Library.
Datejs

How can I convert datetime microformat to local time in javascript?

I have a page that is currently using the datetime microformat to display a timestamp, but I have only been showing the human-readable time for my own time zone:
<abbr class="published" title="2009-01-09T09:16:00-05:00">
Friday, January 9, 2009 at 9:16 am (EST)</abbr>
What I'd like to do is rewrite the innerHTML for the abbr tag to be the same format, but in the user's local timezone. So for a reader in Seattle, the above should be converted to:
<abbr class="published" title="2009-01-09T09:16:00-05:00">
Friday, January 9, 2009 at 6:16 am (PST)</abbr>
I've looked at the Javascript Date object, which allows me to get the local timezone offset. But I have a few problems:
I don't see an easy way to create a new Date object from an ISO-8601 timestamp. (I suppose I could parse with substrings or regex if there's no faster way.)
I don't see a way to get the named abbreviation for the timezone. For example, for a reader in Seattle, I'd want the time to have "(PST)" appended to the end, otherwise it is not clear to that user that the timestamp has been converted (especially if he is a frequent visitor and has become accustomed to the fact that my times are in EST).
Here is code of mine that parses an ISO timestamp:
function isoDateStringToDate (datestr) {
if (! this.re) {
// The date in YYYY-MM-DD or YYYYMMDD format
var datere = "(\\d{4})-?(\\d{2})-?(\\d{2})";
// The time in HH:MM:SS[.uuuu] or HHMMSS[.uuuu] format
var timere = "(\\d{2}):?(\\d{2}):?(\\d{2}(?:\\.\\d+)?)";
// The timezone as Z or in +HH[:MM] or -HH[:MM] format
var tzre = "(Z|(?:\\+|-)\\d{2}(?:\\:\\d{2})?)?";
this.re = new RegExp("^" + datere + "[ T]" + timere + tzre + "$");
}
var matches = this.re.exec(datestr);
if (! matches)
return null;
var year = matches[1];
var month = matches[2] - 1;
var day = matches[3];
var hour = matches[4];
var minute = matches[5];
var second = Math.floor(matches[6]);
var ms = matches[6] - second;
var tz = matches[7];
var ms = 0;
var offset = 0;
if (tz && tz != "Z") {
var tzmatches = tz.match(/^(\+|-)(\d{2})(\:(\d{2}))$/);
if (tzmatches) {
offset = Number(tzmatches[2]) * 60 + Number(tzmatches[4]);
if (tzmatches[1] == "-")
offset = -offset;
}
}
offset *= 60 * 1000;
var dateval = Date.UTC(year, month, day, hour, minute, second, ms) - offset;
return new Date(dateval);
}
Unfortunately, it doesn't handle timezone abbreviations either. You would have to modify the "tzre" expression to accept letters, and the only solution I know of to deal with timezone abbreviations in Javascript is to have a look-up table which you keep up to date manually in the event of changes to regional daylight savings times.
EcmaScript formalized the addition of an ISO-8601 style string as an imput for a JavaScript date. Since most JS implementations don't support this, I created a wrapper to the Date object, that has this functionality. If you set the title tags to output in UTC/GMT/Z/Zulu offset, you can use my EcmaScript 5 extensions for JS's Date object.
For DateTime values that are to be used in client-side scripts, I generally try to always do the following. Store date+time in UTC zone (even in databases). Transmit date-times in UTC zone. From client to server, you can use the .toISOString() method in the above link. From server-to client this is relatively easy.
Via jQuery (with extension):
$('.published').each(function(){
var dtm = new Date(this.title);
if (!isNaN(dtm)) {
this.text(dtm.toString());
}
});
I don't recall if I added support for non-utc date-times in the input, but wouldn't be too hard to account for them.

Categories

Resources