使用自定义格式的时刻格式化日期

时间:2017-03-07 01:44:14

标签: javascript node.js momentjs

var format = 'EEEE, D 'de' MMMM 'de' Y'
moment(date).format(format);

我有自定义格式并与moment一起使用并获得此

exp: segunda-feira, 2 de janeiro de 2017
act: Segunda-feira, 2 11 Janeiro 11 2017

注意实际解析的模式中的占位符de。 有没有办法让我以预期的格式segunda-feira, 2 de janeiro de 2017使用时刻获取日期?

2 个答案:

答案 0 :(得分:3)

您必须使用[]方括号来转义格式字符串中的字符,请参阅format docs:

  

要转义格式字符串中的字符,可以将字符包装在方括号中。

此外请注意,目前没有EEEE令牌,但单E代表星期几(ISO),因此在您的情况下,您将拥有{{} 1}}。使用2222获取所需的输出。

这是一个工作示例:



dddd

var date = '2017-01-02';
var format = 'dddd, D [de] MMMM [de] YYYY';
console.log(moment(date).format(format));




答案 1 :(得分:0)

格式字符串中的escape characters,可以将字符包装在方括号中。



ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
KEY = 3;


runCaeserCipher(KEY);

function runCaeserCipher(key){

// ask your user for the message to be encrypted.
var message = prompt("What text would you like to encrypt?");
message = message.toUpperCase(); //make sure all characters are uppercase
// create secretMessage by passing message through the encrypt function
var secretMessage = encrypt(message,key);
console.log("The encrypted message is: " + secretMessage + "\n");

// decrypt the secret message by passing secretMessage through the decrypt     function
var decryptedMessage = decrypt(secretMessage,key);


// check to see if the original and decrypted messages are the same
if (message == decryptedMessage){
    console.log("You successfully decoded the message!");
}
else{
    console.log("Something went wrong...");
    console.log("Your original message was \"" + message + "\", but your decrypted message is \"" + decryptedMessage + "\".");
}
}


function encrypt(data, key){
// write your code to encrypt the function here
// HINT: use indexOf to search for the index of a specific character within     the ALPHABET
var encryptedMessage = "";

//look at every character in the message
for (i = 0; i < data.length; i++){
    //save whatever is 3 spaces after the current char
    encryptedMessage += data.indexOf(i+3);
}   
return encryptedMessage;
}
function decrypt(data, key){
var decryptedMessage = "";

// write your code to decrypt the function here
for (i = 0; i < data.length; i++){
    //save whatever is 3 spaces after the current char
    decryptedMessage += data.indexOf(i-3);
}   
return decryptedMessage;
}
&#13;
var momObj = moment();
var format = 'EEEE, D [de] MMMM [de] Y';
var fString = momObj.format(format);
console.log(fString);
&#13;
&#13;
&#13;