How to Get 'a.m.' format in moment.js - javascript

I'm having trouble to find the format for making like :
6 a.m.
I'm wondering if someone know which string i need to enter to outputFormat
for make it the format as describe.
moment(openTime, inputFormat).format(outputFormat)
This format:
'a.m.'

Moment.js doesn't have the exact format output you want, but you can produce it using two .replaces afterwards.
var m = moment();
var s = m.format('h a');
console.log(s);
s = s.replace('am', 'a.m.').replace('pm', 'p.m.');
console.log(s);
m = m.add(12, 'hours');
s = m.format('h a');
console.log(s);
s = s.replace('am', 'a.m.').replace('pm', 'p.m.');
console.log(s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.28.0/moment.min.js"></script>

Related

Javascript - reorder and reformat date

I have a date displaying on my website in this format:
MM/DD/YY
I would like to convert it to the following format using jQuery:
YYYY-MM-DD
I would prefer to do it without a plugin. I was able to replace the forward slashes with hyphens using the code below but now I am stuck.
var date = "05/23/21";
var formattedDate = date.replace(/\//g, '-');
$('body').append(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
To do what you require you can convert the input string to a Date object, then use the methods JS exposes to pull out the constituent parts in to the format you require:
let input = "05/23/21";
let date = new Date(input);
const zeroPad = (num, places) => String(num).padStart(places, '0')
let formattedDate = `${date.getFullYear()}-${zeroPad(date.getMonth() + 1, 2)}-${zeroPad(date.getDate(), 2)}`;
$('body').append(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This method assumes all dates are 20XX. It splits the date by /, reverses that array (getting the YY MM DD format), then reformats the year to be YYYY and joins the array back together with -
var date = "05/23/21";
var formattedDate = date.split('/').reverse().map((e, i) => i === 0 ? `20${e}` : e).join('-');
$('body').append(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
By using regex group and replace it with reverse order you can do it.
var date = "05/23/21";
const formattedDate = date.replace(/(\d+)\/(\d+)\/(\d+)/, "20$3-$2-$1");
console.log(formattedDate);
.as-console-wrapper{min-height: 100%!important; top: 0}
Please check the following code. Let me know if something goes wrong
const d = date.split("/");
var res = '20'+d[2] +'-'+d[0]+'-'+d[1];

Parsing a date in javascript

First of all thanks in advance for helping, the community is great.
I have a problem parsing my date and time. Here is my code:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var string1 = date[1].match(/^\d{4}\-\d{2}-\d{2}/);
var string2 = date[2].match(\s(\d{2}\:\d{2}\:\d{2}));
var string3 = date[3].match(\s(\+\d{4}));
var parts1 = string1.split("-");
var parts2 = string2.split(":");
if (parts1 && parts2)
{
var dt = new Date(parseInt(parts1[0], 10), parseInt(parts1[1], 10) - 1, parseInt(parts1[2], 10), parseInt(parts2[3], 10), parseInt(parts2[4], 10), parseInt(parts2[5], 10));
}
date_final = dt;
}
date_final is defined elsewhere, and is in Date Time Picker format, and here is the input I am trying to parse:
blabla
== date ==
2016-02-13 16:22:10 +0200
blabla
Every time I execute the code, I get a parsing problem. The variable date_final cannot handle the parsed date. What do you think is missing from this code?
Update:
Here is what I'v etried out. Impossible for me to locate what's wrong:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var initial = date[1];
var formated = initial.substring(0, 19);
var final = formated.replace(/-/g, '/');
var last = new Date(final);
Field = last;
logging += "{date=" + Field + "}";
}
The code is actually parsing an email and sending the result over SSL. What surprises me the most is that the logs keep posting the following output of the date i naddition to the "parsing issue": date=Sat Feb 27 2016 16:22:10 GMT+0200 (CEST).
Do you think the problem comes from the code or could be related to how the appliance this code implemented on can handle it?
Thanks
Jane
Sorry for answering in comment.
Here's one solution to your question:
var dateStr = '2016-02-13 16:22:10 +0200';
// get yyyy-MM-dd HH:mm:ss
var formatedStr = dateStr.substring(0, 19);
// get yyyy/MM/dd HH:mm:ss in case of working on most of the browsers
var finalStr = formatedStr.replace(/-/g, '/');
// Date object can easily parse the datetime string we formated above
var date = new Date(finalStr);
Date object can parse complex strings.
Mail providers usually follow an RFC on how timestamps should be written, thus allowing other programming languages to heavily support it.
Just pass your string into date object and it will convert it for you.
let mailStr = `blabla
== date ==
2016-02-13 16:22:10 +0200
blabla`;
let regex = mailStr.match(/\=\= date \=\=\s*(.*[^\s*])/);
let dt = new Date(regex[1]);
console.log(dt);
The output is described in ISO-8601

How to find the number of days difference using Google Script

I was trying to find the difference between two days, I'm getting NaN.
function formatDate(oldFormat,duration,timestamp){
var formattedDate = Utilities.formatDate(oldFormat, "IST","yyyy,MM,dd");
Logger.log(timestamp);
var newDate=new Date(timestamp*1000);
Logger.log(newDate);
newDate=Utilities.formatDate(newDate,"IST","yyyy,MM,dd");
Logger.log(formattedDate);
Logger.log(newDate);
var date1=new Date(formattedDate).getTime();
Logger.log(date1)
var date2=new Date(newDate).getTime();
Logger.log(date2)
var diff=daydiff(date2,date1);
Logger.log(diff); }
function daydiff(first, second) {
return (second-first)/(1000*60*60*24);}
How to find the difference between two date in days? I've date in this format :
date 1 : 2015,05,12
date 2: 2015,05,28
There is no point to use Utilities.formatDate() as it is meant to convert a normal date in to any format, not the other way round.
Also not sure what (oldFormat,duration,timestamp) stand for. You do not use duration in your script, and both dates you showed seem to be the same format.
If you are simply trying to find the difference between two dates, try this:
function formatDate(date1,date2){
date1 = new Date(fixDate(date1));
date2 = new Date(fixDate(date2));
var diff = (date2-date1)/(1000*60*60*24);
return(diff);
}
function fixDate(date){
var collector = date;
if (collector.match(",")!=null){
collector = collector.split(",");
var myString = [collector[1], collector[2], collector[0]].join("/");
return myString
}
}

Converting UTC date to mm/dd/yyyy

I am having a date in isoUtc format and I want to convert it into mm/dd/yyyy format. I tried to use the hint given in this blog entry but the problem I am facing is that if I convert 2007-04-06T00:00Z it gives different dates when user time zone is different. I want that it should give 04/06/2007 always independent of the user timezone.
Any help is appreciated
var d = '2007-04-06T00:00Z';
var d2 = d.substring(5,7)+'/'+d.substring(8,10)+'/'+d.substring(0,4);
// outputs 04/06/2007
You could thy this, if you have always constant format:
var dateString = '2007-04-06T00:00Z',
dateRegExp = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/,
match = dateString.match(dateRegExp),
date;
if (match) {
date = new Date(match[1], match[2] - 1, match[3], match[4], match[5]);
console.log(date);
}
DEMO

Split string to get hours

var date = '28/05/2011 12:05';
var elem = date.split('');
hours = elem[0];
I have the above date format, please tell me how to split this, so that I can obtain 12 (hours) from this string?
var date = '28/05/2011 12:05';
var hrs = date.split(' ')[1].split(':')[0];
You can use a single call to split each component using a regular expression:
var date = '28/05/2011 12:05';
var elem = date.split(/[/ :]/);
alert(elem[3]); //-> 12
Working example: http://jsfiddle.net/gZ9c7/
A RegEx solution:
var myRe = /([0-9]+):[0-9]+$/i;
var myArray = myRe.exec("28/05/2011 12:05");
alert(myArray[1]); // 12
Some additional info:
Working code sample here.
About RegEx in JS.
As long as it's a consistent format:
var hours = date.split(' ')[1].split(':')[0]
is pretty easy.
when working with Dates it's better to use dedicated date/time functions:
var date = '28/05/2011 12:05';
var ms = Date.parse(date)
alert(new Date(ms).getHours())

Categories