How to format the current date format in Vue.js - javascript

I need to get the current date in Vue.js.
For that, I used the following method.
today_date: new Date().toJSON().slice(0,10).replace(/-/g,'.')
today_date will give the date as 2019.09.11 format.
Is there any method to customize this format? Actually I need to get the date as 11.09.2019 format. But it's better to know whether there are solutions to get the date in several formats.

In pure Javascript you should hard code the format that you want by getting the day, month and year, and concatenate them to get what you want, but i recommend to use the moment.js library to format the date easily like :
moment().format('MMMM Do YYYY, h:mm:ss a'); // September 11th 2019, 10:52:10 am
moment().format('dddd'); // Wednesday
moment().format("MMM Do YY"); // Sep 11th 19
moment().format('YYYY [escaped] YYYY');

Can be done in different ways One brilliant lib: MomentJS (which can take care of a lot of formats, locales and operations too), but one solution using pure JS could be:
function dtFormatter(d) {
const yr = d.getFullYear();
const mnt =
d.getMonth() + 1 < 9 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1;
const day = d.getDate() < 9 ? "0" + d.getDate() : d.getDate();
return day + "." + mnt + "." + yr;
}
console.log(dtFormatter(new Date()));

Related

Convert a AM/PM date string to JavaScript date using jQuery

I have a date string like this 20/09/2018 12:00 AM. I need to stop to put the previous date than today. I have searched the web for it, but no answer found with this format.
I need the default date format of JavaScript so that I can compare with new Date() value. When I use the following format it show the message that says invalid date because of my dd/MM/yyyy hh:mm tt format.
alert(new Date("20/09/2018 12:00 AM"));
Igor recommended using moment.js to solve this — it is a widely used date/time library.
With moment.js you can do this:
var m = moment("20/09/2018 3:14 PM", "DD/MM/YYYY h:mm a");
var d = m.toDate();
The first line creates a "moment" object by parsing the date according to the format string specified as the second argument. See http://momentjs.com/docs/#/parsing/
The second line gets the native javascript Date object that the moment object encapsulates; however, moment can do so many things you may not need to get back that native object.
See the moment docs.
Your format isn't valid, thus you're getting invalid date error. So, using your format(dd/MM/yyyy hh:mm tt) we'll grab the year, month, day, hours and the minutes, then we'll reformat it as an acceptable format by the Date constructor and create a Date instance.
Here's a function that do all what being said and returns a Date instance which you can compare it with another Date instance:
function convertToDate(str) {
// replace '/' with '-'
str = str.replace(/\//ig, '-');
/**
* extracting the year, month, day, hours and minutes.
* the month, day and hours can be 1 or 2 digits(the leading zero is optional).
* i.e: '4/3/2022 2:18 AM' is the same as '04/03/2022 02:18 AM' => Notice the absence of the leading zero.
**/
var y = /\-([\d]{4})/.exec(str)[1],
m = /\-([\d]{2}|[\d])/.exec(str)[1],
d = /([\d]{2}|[\d])\-/.exec(str)[1],
H = /\s([\d]{2}|[\d]):/.exec(str)[1],
i = /:([\d]{2})/.exec(str)[1],
AMorPM = /(AM|PM)/.exec(str)[1];
// return a Date instance.
return new Date(y + '-' + m + '-' + d + ' ' + H + ':' + i + ' ' + AMorPM)
}
// testing...
var str1 = '20/09/2018 12:00 AM';
var str2 = '8/2/2018 9:00 PM'; // leading zero is omitted.
console.log(convertToDate(str1));
console.log(convertToDate(str2));
The Date depends on the user's/server's location, two users may have
different results.
Learn more
about Date.
Hope I pushed you further.

C# convert long datetime to get compatible with sql server datetime, date is coming from javascript [duplicate]

This question already has answers here:
Convert JavaScript Date to .NET DateTime
(4 answers)
Closed 5 years ago.
I am passing in a long date from javascript through web api and the date needs to be converted to end up being compatible with C# and then SQL Server datetime field.
This is What is getting passed in
Fri Sep 15 2017 00:11:44 GMT-0700 (US Mountain Standard Time
So I was just trying to do a Convert.ToDateTime
DateTime c = Convert.ToDateTime("Fri Sep 15 2017 00:11:44 GMT-0700 (US Mountain Standard Time)");
Says its not a valid DateTime, and if I don't use convert , then error is that I cannot convert a long to a string.
This probably needs to first be converted in javascript as I think that it will blow up with C# DateTime
However 2017-09-15T07:11:44.000Z is not correct from javascript is it?
From your example it also looks like you want to convert the local time into the equivalent GMT time. If this is the case, there's a great JavaScript library for date/time manipulation, moment.js, which will do that for you. moment().toISOstring() will take the JS user's current date time and give you a zulu time in ISO format.
string source = "Fri Sep 15 2017 00:11:44 GMT-0700";
var result = DateTimeOffset.ParseExact(
source.Replace("GMT", ""),
"ddd MMM dd yyyy HH:mm:ss zzz",
CultureInfo.CurrentCulture);
Use this piece of code to convert JavaScript long date to C# compatible format(dd/MM/yyyy):-
var date = new Date();
var newformateddate = function (date) {
var year = date.getFullYear();
var month = date.getMonth();
month++;
if (month < 10) {
month = "0" + month;
}
var day = date.getDay();
if (day < 10) {
day = "0" + day;
}
document.write(day + " / " + month + " / " + year);
}
Parse datetime with formate is the base way to convert it.
DateTime.ParseExact(dateString.Substring(0,24),
"ddd MMM d yyyy HH:mm:ss",
CultureInfo.InvariantCulture);

New date() returning next date instead of today's date

i am trying to convert a string into date type.i am giving the string value to new date().
but it's returning next day date instead of date which i am trying to convert.
var endDate = new Date("2017-03-23T23:59:59.000Z");
//end date value is now ------ Fri Mar 24 2017 05:29:59 GMT+0530 (India Standard Time).
Please suggest me how can get correct date in the format MM/DD/YYYY
This hack can help you,
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
it will give you,
"2017-03-23T23:59:59.000Z"
Further if you want to convert it to DD/MM/YYYY then you can use native javascript or lib like moment for that,
This simpile js will help to convert it to any format.
var endDate = new Date("2017-03-23T23:59:59.000Z").toISOString();
var d1 = endDate.split('T'); //spliting date from T
var d2 = d1[0].split('-'); //getting date part
console.log('yyyy/MM/dd', d2[0] + "/" + d2[1] + "/" + d2[2]) //YYYY/MM/DD
console.log("DD/MM/YYYY", d2[2] + "/" + d2[1] + "/" + d2[0])
jsfiddle link
if your time is in IST use below
var endDate = new Date("2017-03-23T23:59:59.00+0530");
If you check dates, you will see that your dates differs in 5h 30 mins, that is same as your date saying GMT +0530. Your original date has .000Z that is time zone of GMT +0.
Make sure you use same time zone when working with date.
Try using Date.UTC('your date')
JavaScript Date objects carry no timezone information. The only reason you saw a non-UTC date is that the browser chooses by default to display dates as local time in the console. If you don't care about the date object aligning with the exact instant in local time, you can use the following format function to turn it into MM/DD/YYYY format:
function format (date) {
var mm = ('0' + (date.getUTCMonth() + 1)).slice(-2)
var dd = ('0' + date.getUTCDate()).slice(-2)
var yyyy = date.getUTCFullYear()
return mm + '/' + dd + '/' + yyyy
}
var endDate = new Date("2017-03-23T23:59:59.000Z")
console.log(endDate.toISOString())
console.log(format(endDate))
(Credit to Ranj for posting an answer using Date#toISOString before mine.)
I have created the solution over here please find below link
https://www.w3schools.com/code/tryit.asp?filename=FD0YSGRMB59W

Parse & format javascript date: dd M YYYY to YYYY-mm-dd

I have a date which looks like:
30 Apr 2015
How do I parse and display the date like this (without Moment.js)?
2015-04-31 (or YYYY-mm-dd)
The easiest thing to do might be to use moment.js.
If you prefer rolling your own solution in vanilla JS, this will work:
var padZero = function (integer) {
return integer < 10 ? '0' + integer : '' + integer
};
var myDate = new Date('30 Apr 2015');
var myDateString = myDate.getFullYear() + '-' +
(padZero(myDate.getMonth()+1)) + '-' +
(padZero(myDate.getDate()));
console.log(myDateString); // 2015-04-30
The parsing part is easy...though it'll fail on your example, because there is no 31st day in April :)
var x = new Date("30 Apr 2015");
Formatting the date is a little trickier. You have a few options. Date natively supports several output methods (.toDateString(), .toLocaleDateString(), etc) but none of them match the format you've given. It does, however, allow you to individually select the day, month and year values for the date. So, you can assemble them manually:
console.log(x.getFullYear() + '-' + (x.getMonth()+1) + '-' + x.getDate())
Note here that .getMonth() returns a 0-based index and isn't padded to two digits, and .getDay() gets the day-of-the-week index, not day-of-the-month (which is .getDate()).
However, your better choice is to take a look at moment.js, which provides the ability to format by an arbitrary format string, similar to what you'd expect from other languages. Unless you're unable to introduce another library for some reason, I feel this is a category of problem where it makes sense to use the very nice solution that already exists.
Use moment.js
Convert your date like this:
var myDate = moment("30 Apr 15", "DD MMM YY").format("YYYY-MM-DD");
console.log(myDate);
//2015-04-30
DEMO
you can do that easy with
//define Date
var xdate = "31 Apr 2015";
// simple array to define months from Jan to Dec [01 : 12]
var months = {
Jan:'01',
Feb:'02',
Mar:'03',
Apr:'04',
May:'05'
};
// split our Date and rearrange as yyyy-mm-dd
var reform = xdate.split(' ')[2]+'-'+months.Apr+'-'+xdate.split(' ')[0];
alert(reform);// return 2015-04-31

Why isn't there a standard way to format a date object in javascript?

I have a javascript date object and want to format it like this
2014-12-18
like %Y-%m-%d but I can't seem to find a "good way to achieving this at once. Why does javascript not have a strftime function? How can I achieve what I want?
No need to use an external library:
var now = new Date();
var s = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
alert(s); // 2014-12-18
Explanation:
getFullYear() gives you the 4-digit year
getMonth() gives you the month (0-based, that's why you have to add 1)
getDate() gives you the day of month
You can use library moment. There is no good reason behind lack of Date formatting functions.
This answer contains code to format date as %Y-%m-%d in vanilla JS.
Did you try Moment.js ?
moment.js
Install
bower install moment --save # bower
npm install moment --save # npm
Install-Package Moment.js # NuGet
Format Dates
moment().format('MMMM Do YYYY, h:mm:ss a'); // December 18th 2014, 2:08:59 pm
moment().format('dddd'); // Thursday
moment().format("MMM Do YY"); // Dec 18th 14
moment().format('YYYY [escaped] YYYY'); // 2014 escaped 2014
moment().format(); // 2014-12-18T14:08:59+01:00
Here is the docs
Based on helpermethod's answer, here is a way to do it with 0-padded months and dates:
function pad(num) {
return (num >= 10 ? '' : '0') + num;
}
const now = new Date();
const s = now.getFullYear() + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate());
alert(s); // 2020-04-08

Categories

Resources